Home > Software design >  Is there any way to get the updated state inside a function
Is there any way to get the updated state inside a function

Time:11-10

Let's took a look a this functional component :

note : this is just an exemple

function Foo() {

 const [data, setData] = useState([]);
 
 const GetData = () => {
  //setting the data...
  setData([1, 2, 3]);
 }
 
 const ShowData = (data) => {
  if(data)
     console.log(data);
}

useEffect( () => {
  GetData();
  ShowData(data)
},[]);

console.log(data) // Here I get the new data normally;
return (
<>
 <h2>Hello world ! </h2>
</>
)}

So my question is how can I get the updated value ( the new value of data ) to use it inside ShowData function ?

CodePudding user response:

The best way is to use another useEffect with data as dependency, so everytime data is updated you will run showData() like the following

useEffect( () => {
  GetData(); 
},[]); 

useEffect( () => {
  ShowData()
},[data]); // runs when data is updated

this way you don't need to pass data argument to showData fn. You will get the state updated.

CodePudding user response:

On first render use

useEffect(() => {
  GetData();
},[]);

Then we also add a useEffect with data in the dependency array - which means it will run the code every time data changes.

useEffect(() => {
  ShowData(data)
},[data]);

Since data will be empty on first render you could do something like this in getData to just skip the function if data is not available yet.

const ShowData = (data) => {
   if(!data) return; //if there is no data yet, dont read code below
   
   console.log(data);
}

Jsfiddle demo

  • Related