Tom
Tom

Reputation: 1565

React `useState` hooks - set the state and use it immediately

I understand that changing the state causes the component function to be called again with the new state being derived from the useState hook. Within the function where the state is set, the state remains the same because any functions defined inside it close over that state.

Here's an example of where I'm having trouble finding a good pattern:

  const fetchUsers = async () => {
    const result = await axios.get(
      `http://localhost:3001/get_users/${pageNumber}`
    );
   }

  const loadMore = () => {
    setPageNumber(pageNumber + 1);
    fetchUsers();
  };

Of course this doesn't work because fetchUsers doesn't have access to the updated state.

  const loadMore = () => {
    setPageNumber(pageNumber + 1);
    fetchUsers(pageNumber + 1);
  };

I could do this but it seems less clear. Is there a better way?

Upvotes: 0

Views: 218

Answers (2)

ApplePearPerson
ApplePearPerson

Reputation: 4439

For this you can use the useEffect hook. You can give it a function and an array as parameters. If any of the variables in the array changes (such as a state var you give to it) the function will be called. You'll be able to use the newest pageNumber inside there.

const [ pageNumber, setPageNumber ] = useState(1);

const loadMore = () => {
    setPageNumber(pageNumber + 1);
};

/* Be careful, this function will also run on mount. If you want to prevent that make use of some isMounted boolean inside it. */
useEffect(() => {
    fetchUsers(pageNumber);
}, [ pageNumber ]);

const fetchUsers = async (toFetchPageNumber) => {
    const result = await axios.get(
        `http://localhost:3001/get_users/${toFetchPageNumber}`
    );
}

Upvotes: 1

Mukesh Soni
Mukesh Soni

Reputation: 6668

You can call fetchUsers inside useEffect with pageNumber as the dependency.

useEffect(fetchUsers, [pageNumber])

useEffect will call fetchUsers whenever pageNumber changes.

Upvotes: 1

Related Questions