Drem Edys
Drem Edys

Reputation: 133

Refresh fetch function in Custom Route react-admin

I have CustomRoute which gets params from url and fetches, sets the data. But when I click refresh button on react admin navbar it doesnt fire my fetch function. My code looks like this:

export const MyCustomPage= () => {
  const navigate = useNavigate();
  const params = useParams();
  const id = params.id;
  
  const [data, setData] = useState()
  
  const fetchResults = async () => {
    try {
      const { data } = await getAnswers(id);
    } catch (e) {
      ...
    }
  };

  useEffect(() => {
    fetchResults();
  }, []);


  return (
    <>
      <Title title={`${calculator.name} results`} />
      <DataGrid columns={data}
    
       ....
      />
    </>
  );
};

Maybe I can somehow follow the click of button and force fetch?

Upvotes: 0

Views: 651

Answers (1)

Fran&#231;ois Zaninotto
Fran&#231;ois Zaninotto

Reputation: 7335

React-admin relies on react-query for cache invalidation and request. If you fetch your own data via react-query, react-admin's refresh button will automatically refresh your data.

the react-admin documentation explains how to fetch your API with react-query here:

https://marmelab.com/react-admin/Actions.html#usequery-and-usemutation

In your case, I don't know what getAnswers does, but you should do it via react-query's useQuery hook:


const { data } = useQuery(
   ['getAnswers],
   () => getAnswers(id)
);

You won't need to setState manually, as the data you get is reactive.

Upvotes: 1

Related Questions