Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

116
Visualizações
How to persist the same data even after useQuery key change and component is unmounted & remounted again

I have been stuck with one issue, let's say I have this below custom react query hook.

export const useGetData = () => {
  const { filter } = useSelector((state) => state.filterReducer);

  const queryInfo = useQuery(["filter", filter], () => getData(), {
    staleTime: Infinity,
    cacheTime: Infinity,
    enabled: false,
    keepPreviousData: true
  });

  return {
    ...queryInfo,
    data: useMemo(() => queryInfo.data, [queryInfo.data])
  };
};

so here I'm actually storing the user's filter state in the global redux store and whenever the user makes any changes this will create a new cache with data as undefined. so since this query has been set enabled to false it will not make an API call and the user has to manually click on the apply filter button in the UI in order to get the data, which actually makes refetch call and gets the data update the existing undefined cache with the data returned from the server.

since this query has keepPreviousData set to true it will keep the previous data in the UI. but in the cache, the new filter has been updated with undefined. So now let's say the user doesn't apply the filter (by clicking on the apply filter button), they just change the filter (which actually creates a new cache), and let's say the user unmounts the component and mounts the component again (using a toggle), the previous data which was showing has gone! (because now it's showing undefined)

Is it possible to keep the previous data if enabled: false, keepPreviousData: true, even if the component is unmounted and mounted back again?

here is the reproduced code sandbox - link

I'm stuck with this issue for the past couple of days not sure how to fix it. Any help on this will be highly appreciated thanks in advance.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda