#setState being asynchronimous problem

2 messages · Page 1 of 1 (latest)

frozen knoll
#

In admin panel I have a website object in 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.

random pewterBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)