The post below is about creating a custom hook for fetching data, and it's straightforward.
https://dev.to/patrixr/react-writing-a-custom-api-hook-l16
There is one part though that I don't see how it works.
Why would this hook return results twice? (isLoading=true isLoading=false)
function useAPI(method, ...params) {
// ---- State
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState(null);
// ---- API
const fetchData = async () => {
onError(null);
try {
setIsLoading(true);
setData(await APIService[method](...params));
} catch (e) {
setError(e);
} finally {
setIsLoading(false);
}
};
useEffect(() => { fetchData() }, []);
return [ data, isLoading, error, fetchData ];
}
function HomeScreen() {
const [ users, isLoading, error, retry ] = useAPI('loadUsers');
// --- Display error
if (error) {
return <ErrorPopup msg={error.message} retryCb={retry}></ErrorPopup>
}
// --- Template
return (
<View>
<LoadingSpinner loading={isLoading}></LoadingSpinner>
{
(users && users.length > 0) &&
<UserList users={users}></UserList>
}
</View>
)