Created
December 26, 2020 08:00
-
-
Save zilahir/5f83277f706e6c77636db7dc4869d380 to your computer and use it in GitHub Desktop.
expo loading assets custom wrapper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// some stuff here | |
export type FontSouce = Parameters<typeof Font.loadAsync>[0]; | |
const usePromiseAll = ( | |
promises: Promise<void | void[] | Asset[]>[], | |
cb: () => void | |
) => | |
useEffect(() => { | |
(async () => { | |
await Promise.all(promises); | |
cb(); | |
})(); | |
}); | |
const useLoadAssets = (assets: number[], fonts: FontSouce): boolean => { | |
const [ready, setReady] = useState(false); | |
usePromiseAll( | |
[Font.loadAsync(fonts), ...assets.map((asset) => Asset.loadAsync(asset))], | |
() => setReady(true) | |
); | |
return ready; | |
}; | |
interface LoadAssetsProps { | |
fonts?: FontSouce; | |
assets?: number[]; | |
children: ReactElement | ReactElement[]; | |
} | |
const LoadAssets = ({ assets, fonts, children }: LoadAssetsProps) => { | |
const [isNavigationReady, setIsNavigationReady] = useState(!__DEV__); | |
const [initialState, setInitialState] = useState<InitialState | undefined>(); | |
const ready = useLoadAssets(assets || [], fonts || {}); | |
useEffect(() => { | |
const restoreState = async () => { | |
try { | |
const savedStateString = await AsyncStorage.getItem( | |
NAVIGATION_STATE_KEY | |
); | |
const state = savedStateString | |
? JSON.parse(savedStateString) | |
: undefined; | |
setInitialState(state); | |
} finally { | |
setIsNavigationReady(true); | |
} | |
}; | |
if (!isNavigationReady) { | |
restoreState(); | |
} | |
}, [isNavigationReady]); | |
const onStateChange = useCallback( | |
(state) => | |
AsyncStorage.setItem(NAVIGATION_STATE_KEY, JSON.stringify(state)), | |
[] | |
); | |
if (!ready || !isNavigationReady) { | |
return <AppLoading />; | |
} | |
return ( | |
<NavigationContainer {...{ onStateChange, initialState }}> | |
<StatusBar style="light" /> | |
{children} | |
</NavigationContainer> | |
); | |
}; | |
// some more stuff | |
export default LoadAssets; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment