Home > Mobile >  Forcing a re-render of independent component using react-query
Forcing a re-render of independent component using react-query

Time:10-02

I have this problem.

I have defined two components. One for showing data, another one for searching. They are not connected together, but works independly. I use react-query for getting data from API.

Searchbox:

const SearchBox = () => {

    const { data, status } = useQuery(['planets', searchTerm], () => fetchSearchingResults('planets', searchTerm), { enabled: Boolean(searchTerm)});
...

PlanetsList

const PlanetsList = () => {
    const { data, status } = useQuery('planets', () => fetchResourceData('planets'));

**I change query data in SearchBox by searching and handling local state, it works. But I need call re-render of PlanetsList with data from SearchBox query result. How to do it? Is it possible **

CodePudding user response:

You will need to call the same exact query in PlanetList. Simple rerender won't help because useQuery(['planets', searchTerm]) and useQuery('planets') are completly different cache.

You could try to wrap your planets query in function if both queries gives the same type of result.

const usePlanetsQuery (searchTerm?: string) => {
  return useQuery(['planets', searchTerm], () => searchTerm ? fetchSearchingResults('planets', searchTerm) : fetchResourceData('planets'));
}

const SearchBox = () => {
  const searchTerm = selectSearchTempFromContextOrStateManageOrProps();
  const { data, status } = usePlanetsQuery(searchTerm);

const PlanetsList = ({searchTerm}: {searchTerm: string}) => {
  const { data, status } = usePlanetsQuery(searchTerm);
}
}

It will synchronize your results between SearchBox and PlanetsList

  • Related