Home > Software design >  useEffect not seeing dependency change on single click
useEffect not seeing dependency change on single click

Time:07-21

I am making a call to an Api using the following hook. It returns 10 pictures at a time.

export const useFetchData = (url, page) => {
  const [error, setError] = useState(null)
  const [apiData, setApiData] = useState(null)
  const [loading, setLoading] = useState(false)
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true)
        const res = await axios.get(*****);
        const data = await res.data
        setApiData(data)
      } catch (e) {
        setError(e)
      } finally {
        setLoading(false)
      }
    }
    fetchData()
  }, [page, url])
  return { apiData, loading, error }
}

I am trying to do pagination in the following component by changing the state value of page by using the nextPage and backPage functions.

  let [page, setPage] = useState(1);
  let { apiData, loading, error } = useFetchData(url, page);
  const nextPage = () => {
    setPage(page   );
  };
  const backPage = () => {
    setPage(page --);
  };

  return (
       <div className="photo-display__buttons-container">
          <button onm ouseDown={()=>backPage()}>Back</button>
          <button onClick={()=>nextPage()}>Next</button>
        </div>
      <main className="photo-display">
        <div className="photo-display__container">
          {apiData?.photos.map((photo) => (
            <Photo key={photo.id} photo={photo} />
          ))}
        </div>
    </div>
  );
};

export default App;

By extensive console logging I am able to see that the state value is changed and the hook is called but the try catch does not execute on a single click.

Only if it is double clicked does the try catch execute. The state value is temporarily changed to reflect the double increase but after the hook is called in goes back to the correct value.

Why? and How do i get it to work on a single click?

CodePudding user response:

When you do setPage you are using a postfix , which means the original value will be returned (and then incremented). You need to use a prefix so that it is incremented first, then passed in to setState, or just skip the entirely and do setState(i 1).

Eg (postfix):

let i = 0;
console.log(i  );

Eg (prefix):

let i = 0;
console.log(  i);

CodePudding user response:

Try changing setPage(page ) to setPage(page 1).

  • Related