Reputation: 699
Hi Everyone I am unable to get current state after setting up the state. I am calling a function Where I am passing that state but I am always getting default state in that function. this is my State-
const [currentValue , setCurrentValue] = useState(one[0]); // where one[0] is string "Test"
this is my onchange function -
const getTest = useCallback((newValue:string) => {
setCurrentValue({
label:newValue,
value:newValue
});
getCurrentValue(currentValue.value);
getSortOrder()
}, [])
this is my getSortOrder function -
const getSortOrder =() => {
console.log(currentValue);
}
I am not getting updated state in getSortOrder function & getCurrentValue function. But yes If I am trying to console the state in render then it is showing me updated state but in function it is not updating. How can I achieve the updated state in both functions ?
Upvotes: 5
Views: 3234
Reputation: 571
This is happening because the 'setCurrentValue' function is an asynchronous function and the state is updated after both the functions 'getCurrentValue' and 'getSortOrder' have finished their execution.
One easy solution will be to pass the parameter 'newValue' to both the functions like this :
const getTest = useCallback((newValue:string) => {
setCurrentValue({
label:newValue,
value:newValue
});
getCurrentValue(newValue);
getSortOrder(newValue)
}, [])
const getSortOrder =(newValue) => {
console.log(newValue);
}
Or you can use the 'useEffect' functionality to trigger the functions after the value of the state has been updated like this :
const getTest = useCallback((newValue:string) => {
setCurrentValue({
label:newValue,
value:newValue
});
}, [])
useEffect(() => {
getCurrentValue();
getSortOrder()
},[currentValue]);
Upvotes: 0
Reputation: 484
If I get your question correctly then this might help:
const getTest = useCallback((newValue:string) => {
setCurrentValue({
label:newValue,
value:newValue
});
//try this code doing in useEffect
}, [])
useEffect(() => {
getCurrentValue(currentValue.value);
getSortOrder()
},[currentValue]); //Everytime currentValue changes it will give new state
Upvotes: 1