Created
October 13, 2021 10:14
-
-
Save yarigpopov/8a258ce204bea14cab4133d4fc4377b4 to your computer and use it in GitHub Desktop.
This file contains 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
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