Ragu
Ragu

Reputation: 155

Read the setState value immediately after setting in useEffect React

I want to fetch info from the API in useEffect, set it using setState and immediately use it for further filtering.

the code looks like this:

 const[usersInfo, setUsersInfo] = setState('')
  useEffect(()=>{
  async function fetchUsers(){
  const response = await fetch(`http://localhost:8083/api/patient/findAll`);
  const json = await response.json();
  setUsersInfo(json)
 }
 fetchUsers()    
 console.log('users info', usersInfo)    
},[]) 

I tried to pass the dependency for usersInfo but then it is running in loop.

What can I do it to prevent this behavior?

Upvotes: 1

Views: 591

Answers (1)

hellogoodnight
hellogoodnight

Reputation: 2129

You need to add a second useEffect that detects changes to usersInfo.

  const [usersInfo, setUsersInfo] = setState("");
  
  useEffect(() => {
    async function fetchUsers() {
      const response = await fetch(`http://localhost:8083/api/patient/findAll`);
      const json = await response.json();
      setUsersInfo(json);
    }
    fetchUsers();
    // console.log("users info", usersInfo); // commenting out this code since it will always print empty string
  }, []);

  useEffect(() => {
    if(usersInfo !== ""){
      // Do stuff here with usersInfo
    }
  }, [usersInfo]);

Upvotes: 2

Related Questions