setState being asynchronimous problem
Unanswered
Sun bear posted this in #help-forum
Sun bearOP
In admin panel I have a website object in
When a user is creating a new page he first calls
This is a pseudo code
But the problem is when the
What can I do to fix this problem and if possible without
useState which holds the website, pages, sections, etc.When a user is creating a new page he first calls
addPage function, then the app calls setWebsite server action, which updates the website json object in the database.const [website, setWebsite] = useState(websiteObject)
function addPage(newPage) {
setWebsite((prev) => ({
...prev,
pages: [
...prev.pages,
newPage
]
})
}
addPage(newPage)
await setWebsite(website)This is a pseudo code
But the problem is when the
setWebsite is called the website state has not yet been updated due to setState being somewhat asynchronimous and I end up just setting the website in the database to what it was before adding a new page to it. What can I do to fix this problem and if possible without
fakePromises like sleep, since I don't think this would be a consistent way of adding a webpage since on some computers adding a page could take longer than on others.1 Reply
Sun bearOP
I have taught of making
addPage not directly changing the website state, but instead returning the new website object. This approach would require a bit of refactoring and I would like to avoid it if possible...