Skip to content

Instantly share code, notes, and snippets.

@yarigpopov
Created October 13, 2021 10:14
Show Gist options
  • Save yarigpopov/8a258ce204bea14cab4133d4fc4377b4 to your computer and use it in GitHub Desktop.
Save yarigpopov/8a258ce204bea14cab4133d4fc4377b4 to your computer and use it in GitHub Desktop.
interface State {
data: IDog;
status: Status;
error: Error;
}
const initState: State = { status: Status.loading, data: null, error: null };
const DogDataProviderContext = React.createContext(undefined);
DogDataProviderContext.displayName = 'DogDataProvider';
const DogDataProvider: React.FC = ({ children }): React.ReactElement => {
const [state, setState] = React.useState<State>(initState);
React.useEffect(() => {
setState(initState);
(async (): Promise<void> => {
try {
// MOCK API CALL
const asyncMockApiFn = async (): Promise<IDog> =>
await new Promise(resolve => setTimeout(() => resolve(DATA), 1000));
const data = await asyncMockApiFn();
setState({
data,
status: Status.loaded,
error: null
});
} catch (error) {
setState({
error,
status: Status.error,
data: null
});
}
})();
}, []);
return (
<DogDataProviderContext.Provider value={state}>
{children}
</DogDataProviderContext.Provider>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment