use-http icon indicating copy to clipboard operation
use-http copied to clipboard

Conditional execution of the request

Open danzawadzki opened this issue 5 years ago • 6 comments

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.

  1. One is passed in props from a parent.
  2. 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]
);

danzawadzki avatar Apr 16 '20 19:04 danzawadzki

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"

  1. if path is null then 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])
  1. 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?

iamthesiz avatar Apr 16 '20 21:04 iamthesiz

I'm gonna hold off on this until I get more feedback from this poll.

iamthesiz avatar Apr 23 '20 03:04 iamthesiz

Seems like having a skip would be quite helpful

balthazar avatar Jun 14 '20 07:06 balthazar

having skip would be similar to apollo-client. i think its a must for auto managed state

macrozone avatar Oct 23 '20 09:10 macrozone

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?

nick-keller avatar Mar 23 '21 18:03 nick-keller

I think I have this implemented somewhere in one of the branches

iamthesiz avatar Mar 23 '21 20:03 iamthesiz