useApi.jsx - the correct way to fetch data with react hooks: extension of https://dev.to/nicomartin/the-right-way-to-fetch-data-with-react-hooks-48gc
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
// ./PostList.jsx | |
import React from 'react'; | |
import {apiStates, useApi} from './useApi.jsx' | |
const PostList = () => { | |
const { state, error, data, reload } = useApi('https://api.mysite.com'); | |
switch (state) { | |
case apiStates.ERROR: | |
return ( | |
<React.Fragment> | |
<p>ERROR: {error || 'General error'}</p> | |
<button onClick={() => reload()}>retry</button> | |
</React.Fragment> | |
case apiStates.SUCCESS: | |
return ( | |
<React.Fragment> | |
<p>Data:</p> | |
<ul> | |
{data.map((element) => ( | |
<li>{element.title}</li> | |
))} | |
</ul> | |
</React.Fragment> | |
); | |
default: | |
return <p>loading..</p>; | |
} | |
}; |
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
// ./useApi.jsx | |
import React from 'react'; | |
export const apiStates = { | |
LOADING: 'LOADING', | |
SUCCESS: 'SUCCESS', | |
ERROR: 'ERROR', | |
}; | |
export const useApi = url => { | |
const [data, setData] = React.useState({ | |
state: apiStates.LOADING, | |
error: '', | |
data: [], | |
}); | |
const setPartData = (partialData) => setData({ ...data, ...partialData }); | |
const load = () => { | |
setPartData({ | |
state: apiStates.LOADING, | |
}); | |
fetch(url) | |
.then((response) => response.json()) | |
.then((data) => { | |
setPartData({ | |
state: apiStates.SUCCESS, | |
data | |
}); | |
}) | |
.catch(() => { | |
setPartData({ | |
state: apiStates.ERROR, | |
error: 'fetch failed' | |
}); | |
}); | |
}; | |
React.useEffect(() => { | |
load(); | |
}, []); | |
return [...data, reload: load]; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment