Skip to content

Instantly share code, notes, and snippets.

@Kornil
Created February 16, 2019 14:20
Show Gist options
  • Save Kornil/33d1c3c068002d7f3946d7462a0ebdec to your computer and use it in GitHub Desktop.
Save Kornil/33d1c3c068002d7f3946d7462a0ebdec to your computer and use it in GitHub Desktop.
// Hook reducer
const reducer = (state, action) => {
switch(action.type) {
case 'initial data':
return action.payload;
}
}
// Hook actions
const fetchData = async () => {
const response = await fetch('https://aws.random.cat/meow');
const data = await response.json();
return data;
}
// Component
const Hello = () => {
const [state, dispatch] = React.useReducer(reducer, { file: null });
React.useEffect(() => {
fetchData().then((response) => {
dispatch({
type: 'initial data',
payload: response
});
});
}, []);
return (
<div>
{data.file ? <img src={data.file} /> : <p>loading...</p>}
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment