Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-query cache doesn't persist on page refresh

I would like to set a 24 hours cache once a useQuery request has succeeded.

But as soon as I refresh the page, the cache is gone. I see it because I console.log a message each time the route is hit on my server.

How to prevent this behaviour and implement a real cache?

Here is the code:

   import { useQuery } from "react-query";
import { api } from "./config";

const _getUser = async () => {
  try {
const res = api.get("/get-user");
return res;
  } catch (err) {
return err;
  }
};

export const getUser = () => {
  const { data } = useQuery("contact", () => _getUser(), {
cacheTime: 1000 * 60 * 60 * 24,
  });
  return { user: data && data.data };
};


// then in the component:
  const { user } = getUser();

return (
<div >
  hello {user?.name}
</div>

I've also tried to replace cacheTime by staleTime.

like image 746
DoneDeal0 Avatar asked Jul 12 '26 14:07

DoneDeal0


1 Answers

if you reload the browser, the cache is gone because the cache lives in-memory. If you want a persistent cache, you can try out the (experimental) persistQueryClient plugin: https://react-query.tanstack.com/plugins/persistQueryClient

like image 83
TkDodo Avatar answered Jul 15 '26 02:07

TkDodo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!