use-http
use-http copied to clipboard
Conditional execution of the request
Hi, I have a component that makes a request for data depending on the data it gets from its parent in props, and these also come from an external API. I want to avoid conditional rendering of the component, because I've already made a beautiful skeleton loader for this component! 😄 What I would like to be able to do is to make the conditional request only when the value needed to execute the request is not undefined. This way my component is listening to the two flags informing about the data loading.
- One is passed in props from a parent.
- Second is internal.
What I tried so far looked more or less like this, but for obvious reasons it makes one unnecessary request.
const matchDetails = useFetch<MapEvents>(
{
path: matchId && mapId ? MatchApi.GET_EVENTS(matchId, mapId) : '',
},
[matchId, mapId]
);
I'm still trying to think of a good way to do conditional fetching with auto-managed state.
For now, what you can do is
const { data, get } = useFetch(MatchApi.GET_EVENTS(matchId, mapId))
useEffect(() => {
const shouldFetch = !(typeof matchId === 'undefined' && typeof mapId === 'undefined')
if (shouldFetch) get()
}, [matchId, mapId, get])
OR
const { data, get } = useFetch()
useEffect(() => {
const shouldFetch = !(typeof matchId === 'undefined' && typeof mapId === 'undefined')
if (shouldFetch) get(MatchApi.GET_EVENTS(matchId, mapId))
}, [matchId, mapId, get])
Ideas for solving this via "auto-managed state"
- if
pathisnullthen skip the request
const shouldFetch = !(typeof matchId === 'undefined' && typeof mapId === 'undefined')
const path = shouldFetch ? MatchApi.GET_EVENTS(matchId, mapId) : null
const matchDetails = useFetch<MapEvents>(path, [matchId, mapId, shouldFetch])
- have an option that handles this condition
const shouldFetch = !(typeof matchId === 'undefined' && typeof mapId === 'undefined')
const matchDetails = useFetch<MapEvents>(MatchApi.GET_EVENTS(matchId, mapId), {
skip: !shouldFetch,
}, [matchId, mapId, shouldFetch])
Thoughts?
I'm gonna hold off on this until I get more feedback from this poll.
Seems like having a skip would be quite helpful
having skip would be similar to apollo-client. i think its a must for auto managed state
So according to the poll, having a skip option seems to be the more popular choice, probably because it is what apollo-client uses.
Any news on this?
I think I have this implemented somewhere in one of the branches