Skip to content

Instantly share code, notes, and snippets.

@WillMayger
Last active November 7, 2019 22:58
Show Gist options
  • Save WillMayger/85b8205e5a786bd223d115a320d563a3 to your computer and use it in GitHub Desktop.
Save WillMayger/85b8205e5a786bd223d115a320d563a3 to your computer and use it in GitHub Desktop.
Dynamic import hook for flags
// @flow
import { useState, useEffect } from 'react'
// for dynamically importing all flags
export async function createFlagStore(ary: { node: { iso_country_code: string } }[] | any): Promise<Map<string, string>> {
const promises = ary.map(({ node: { iso_country_code } }) =>
import(`../static/images/flags/${iso_country_code.toLowerCase()}.png`)
.then((item) => ({
iso_country_code,
flag: item.default,
}))
)
const flagArray = await Promise.all(promises)
const flagStore = new Map()
flagArray.forEach(({ flag, iso_country_code }) => {
flagStore.set(iso_country_code, flag)
})
return flagStore
}
type Props = {|
allRoamingPrice: {
edges: {
node: {
iso_country_code: string
}
}[]
}
|}
// hook to use
// usage:
// const flagStore = useFlagStore(data)
export default function useFlagStore(data: Props | any): null | Map<string, string> {
const [flags, setFlags] = useState(null)
useEffect(() => {
(async () => {
const store = await createFlagStore(data.allRoamingPrice.edges)
setFlags(store)
})()
}, [])
return flags
}
// hook to get individual flags
export function useFlag(iso_country_code: string): string {
const [flag, setFlag] = useState('')
useEffect(() => {
(async () => {
const flagModule = await import(`../static/images/flags/${iso_country_code.toLowerCase()}.png`)
setFlag(flagModule.default)
})()
}, [])
return flag
}
@WillMayger
Copy link
Author

Creates a store awaiting for all import promises then adding them into a Map with key value pairs.
It then creates a hook to store the flag store in state on did mount to prevent it from being triggered for every re-render.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment