DEV Community

Ali Bahaari
Ali Bahaari

Posted on

How to re-fetch data when something changes in React.js?

React.js Image

Assume you have a list in your web application which you would allow the clients to manipulate the list records by removing, editing and adding. What happens if data would change?!
Often we should update data behind the scene and silently.
There are 2 ways which I'll be showing you.

Method 1

In fact, this method is not the subject of our article but I'll explain.

Consider you would fetch data from an API. You would use state management systems like Redux, Redux Toolkit and etc. After that, you would manipulate data there and the list would be updated. But wait a minute...
What about a list which is needed to be updated synchronously?! Sure! The list is outdated and is not efficient.

Method 2

Re-fetching is the key of our process. But the main question is:
How should I know data would change?!

1- OK! First of all, you must declare a state by using useState, Redux and etc. The default value should be boolean which in my case is a false.

const [toggle, setToggle] = useState(false);
Enter fullscreen mode Exit fullscreen mode

2- Consider the clients commence to add records. When POST method of an API executed, the state should be toggled by negating the previous state value.

setToggle(prevState => !prevState);
Enter fullscreen mode Exit fullscreen mode

3- What now?! Write useEffect for fetching the data again while dependency variable has been set to toggle state.

useEffect(() => {
    // Fetching
}, [toggle])
Enter fullscreen mode Exit fullscreen mode

BOOM! Because of changing the toggle state after every change you've specified, the data will be fetched again and nicely without doing this manually by for example clicking on a button and etc.

You can or may want to connect with me through the networks I've put on my website: Ali Bahaari's Website

Discussion (0)