Home > Blockchain >  React component state variable updated but the fetch data is not triggered
React component state variable updated but the fetch data is not triggered

Time:12-21

I have a very simple view component, in which I use useSWR to fetch data to show.

In short the useSWR hook is a HTTP cache invalidation strategy that wraps the fetch.

export const MyViewComponent = (props: {... }) => {
  // I have a state variable 'page'
  const [page, setPage] = useState(1); 

  // fetches the data from backend
  const { data, error } = useSWR('/my/products', () => {
      fetchMyData(baseUrl, page)
  );

  // button click callback
  const onBtnClick = ()=> {
     setPage(page 1)
  }
  return <div>
       ...
       <button onClick={() => onBtnClick()}>Next</button>
  </div>
}

As you can see, I have a page state, I wished that every time when the button is clicked, the useSWR wrapped function fetchMyData(baseUrl, page) will be triggered to fetch data again for the new page number.

However, the behaviour now is that the component does get re-rendered when button clicked, but the fetchMyData(baseUrl, page) is not triggered at all.

How to fix it to have the fetch data be triggered when setPage(...) is called?

CodePudding user response:

It looks like you're trying to do pagination. Here is SWR's page on pagination: https://swr.vercel.app/docs/pagination

You need to include the page state variable in the string you pass as your useSWR hook's first argument. Then the hook should take care of the rest.

const someFetcherFunction = (url) => {
  // fetch and return data from url
};

const MyComponent = () => {
  const [page, setPage] = useState(1);
  const { data, error } = useSWR('/my/products?page=${page}', someFetcherFunction);

  const onBtnClick = () => { setPage(prev => prev   1); };

  return <button onClick={() => onBtnClick()}>Next</button>;
};
  • Related