r/learnreactjs • • Mar 21 '22
Help with async function please
Hi, I am trying to make this function async in react so that after I call my setInfo (state setting function) it then sends info.portfolio to localStorage. Right now, it just sends the empty array because the async function for setting state has not finished yet. Any ideas on how to achieve this? If I move the localStorage setting outside the function to just a separate line, then it works but that does not fix the problem since then every time you load the page it resorts info.portfolio back to its original empty state array. thank you!
const handleSubmit = async (e) => {
e.preventDefault();
try {
let currency = info.active_currency
let amount = info.amount
const data = await axios.post('http://localhost:3000/calculate',
{ id: currency.id, amount: amount })
setInfo(state => ({
...state,
portfolio: [...state.portfolio, data.data],
active_currency: null,
amount: ''
}))
localStorage.setItem('portfolio', JSON.stringify(info.portfolio))
} catch (err) {
console.log(err)
}
}
View all comments
Show parent comment
1
u/Saf94 Mar 22 '22
Your problem is you’re not initialising the state to be what the value is in your local storage when your component is mounted. You need to, when you create your useState, make the default value equal to localStorage.getItem(…)