user3568611
user3568611

Reputation: 141

How to improve this react-query multiple queries conditionally called code

I have a component that takes router urls params and trigger calls depending on these params.

Here's how I made it

const {
  data: data1,
  isLoading: isLoading1,
  isError: isError1,
} = useQuery({
  queryKey: [`test-${props.match.params.language}`],
  queryFn: () =>
    fetch(
      `${BASE_URL}${API_URLS.GET_QUIZ}/?languages=${props.match.params.language}&level=${props.match.params.difficulty}`
    ).then((response) => response.json()),
  enabled: props.match.params.source === "api",
});

const {
  data: data2,
  isLoading: isLoading2,
  isError: isError2,
} = useQuery({
  queryKey: [`test-${props.match.params.language}`],
  queryFn: () => {
    console.log("intoQuery");
    return fetch(
      `${BASE_URL}${API_URLS.TEST}/${props.match.params.language}`
    ).then((res) => res.json());
  },
  enabled: props.match.params.source === "intern",
});

useEffect(() => {
  console.log("data2", data2);
  console.log("data1", data1);
  if (props.match.params.source === "api") {
    setData(() => data1);
    setIsloading(isLoading1);
    setIsError(isError1);
  }
  if (props.match.params.source === "intern") {
    setData(() => data2?.questions || []);
    setIsloading(isLoading2);
    setIsError(isError2);
  }
}, [data1, data2]);

It works but I find that the code is redundant, and there is much boiterplate.

I would like to know if is possible to optimise it better and only return one {data, isLoading,IsError} object instead of having {data1, isLoading1,IsError1} and {data2, isLoading2,IsError2}

I very simple solution is to conditionally set the url.

But I would like to know it these is other ways

Upvotes: 1

Views: 350

Answers (1)

TkDodo
TkDodo

Reputation: 28733

const { data, isLoading, isError } = useQuery({
  queryKey: ['test', props.match.params.language, props.match.params.difficulty],
  queryFn: () =>
    fetch(
      `${BASE_URL}${API_URLS.GET_QUIZ}/?languages=${props.match.params.language}&level=${props.match.params.difficulty}`
    ).then((response) => response.json())
});

if the props change, so will your query key, and it will trigger a new fetch.

Upvotes: 1

Related Questions