DEV Community

Discussion on: setState in Reactjs is not a function

saiavinashiitr profile image
Sai Avinash Duddupudi Author • Edited on
useEffect(() => {
    person !== null && setCustomers({data: person, isLoading: true, filteredData: person});
    }, [person])
Enter fullscreen mode Exit fullscreen mode

By dependency, you mean the above block of code gets called every time until person state is changed?

Thread Thread
buraksaraloglu profile image
Burak Saraloglu

It works like this:
1-) Initial page rendering with empty person state, then renders your fetch effect (the second effect did not process because person === null)
2) After the first effect process is done, it will change the person and we put the person state as a dependency for the second effect, it will re-render. Then obviously it will re-render the part of the document.

So, it will not get called until the person state is changed. It will get called if the person state changes.

Thread Thread
saiavinashiitr profile image
Sai Avinash Duddupudi Author • Edited on

Since we added person as dependency , you said it will re-render when person state is updated. so there might be chances of hitting the API twice right? depending upon the person state?

Please correct me If I am wrong

Thread Thread
buraksaraloglu profile image
Burak Saraloglu

As far as I remember, we should've written API connection in separate effect. So, It shouldn't hit for API twice. It will only recall for customers effect.

PS: There's a solution below: after you call for API, setPerson and setCustomers.

.then((data) => {
setPerson(data);
setCustomers(data) // You Need this For set Person to state person
});

Maybe this can work aswell.