<Button
onClick={() => {
console.log('addedNodes', addedNodes)
let credentials = //something...
let nodes = [...addedNodes]
console.log(addedNodes)
setCurrentForm(
{
...currentForm,
credentials: credentials,
nodes: [...addedNodes],
}
)
}}
</Button>
I have a button that updates the currentForm
state using another state addedNodes
.
Whenever the currentForm
gets updated, I console.log the currentForm
using useEffect
.
useEffect(() => {
console.log('currentForm ,,,,,, ', currentForm)
console.log('addedNodes ,,,,,, ', addedNodes)
}, [currentForm]);
This prints out the CORRECT updated state.
However, when I try to add an API request using that state, it goes back to the state before it got updated.
For example, when I update my useEffect
to
useEffect(() => {
console.log('currentForm,,,,,, ', currentForm)
console.log('addedNodes ,,,,,, ', addedNodes)
console.log('RUNNING POST')
setLoadingStatus('loading')
let body = {
form: currentForm,
}
intializeForms()
let options = {
headers: header,
method: 'post',
mode: 'cors',
body: JSON.stringify(body),
}
console.log('options.body', options.body)
const urls = ['...'];
const fetchJson = url => fetch(url, options).then(res => res.json());
Promise.all(urls.map(fetchJson))
.then(([result]) => {
...
})
.catch(err => {
setLoadingStatus('none')
console.log(err)
});
}, [currentForm]);
The console.log('options.body', options.body)
prints out the old currentForm
.
This is very weird to be because console.log(currentForm)
prints the expected state, but when I actually use it for an API call, it goes back to the original form.
I assume that it is because this useEffect
gets called everytime the state gets updated, but not really sure.
Any help, please?
useEffect
callback is going to run every time thecurrentForm
value changes, not when any other values change – Bill MetcalfuseEffect
gets the rightcurrentForm
but doesn't pass the right thing to the body – Dawn17initializeForms()
or move into.then
– xadmthen
work inuseEffect
? Is it something like... [currentForm]).then( ... )
? – Dawn17