0

I've been struggling with this one for 2-3 days and hope someone can help. I am moving a blog project over from React to Next, and in one particular case a setState function isn't working.

The code below lives in the _app.tsx function at the top of my project. The editPost function is called from a button in a child component. The code pulls the selected blog post from the database then updates the state of postToEdit. This data is meant to be injected into an edit form via props-- and works fine in the React version of the blog.

In this case, the setState (setPostToEdit) function seems to do nothing. In the console.log function after setPostToEdit(newPostToEdit), you can see that the data has been pulled from Postgres correctly, but the state doesn't change.

In the deletePost and getPosts function in this same _app component, everything works fine. Weird! Any help sincerely appreciated, I'm new to both React and Next.

import '../styles/globals.css'
import React, { useState, useEffect } from 'react'
import type { AppProps } from 'next/app'
import Layout from '../components/Layout'

export default function App({ Component, pageProps }: AppProps) {
  const initPostToEdit = {
    post_id: '',
    title: 'initial post title',
    sub_title: '',
    main_content: '',
    post_url: 'initial URL',
    page_title: '',
    meta_description: '',
    meta_keywords: ''
  }

  const [posts, setPosts] = useState([]);
  const [postToEdit, setPostToEdit] = useState(initPostToEdit);
  const [blogValues, setBlogValues] = useState(initPostToEdit);

  const deletePost = async (id) => {
    try {
      await fetch(`http://localhost:5001/blog-edit/${id}`, {
        method: "DELETE"
      })
      setPosts(posts.filter(post => post.post_id !== id))

    } catch (error) {
      console.error(error.message)
    }
  }

  const editPost = async (id) => {
    try {
      const response = await fetch(`http://localhost:5001/blog-edit/${id}`, {
        method: "GET"
      })
      const newPostToEdit = await response.json()
      
      setPostToEdit(newPostToEdit)

      console.log('postToEdit:', newPostToEdit[0], postToEdit)

      window.location.assign("/admin/blog-edit");

    } catch (error) {
      console.error(error.message)
    }
  }

  const getPosts = async () => {
    try {
      const response = await fetch("http://localhost:5001/blog-edit");
      const jsonData = await response.json();
      setPosts(jsonData);
    } catch (error) {
      console.error(error.message)
    }
  }

  useEffect(() => { getPosts(); }, [])

  return (
    <div>
      <Layout>
        <Component
          {...pageProps}
          editPost={editPost}
          postToEdit={postToEdit}
          setPostToEdit={setPostToEdit}
          blogValues={blogValues}
          setBlogValues={setBlogValues}
          posts={posts}
          deletePost={deletePost}
        />
      </Layout>
    </div>
  )
}
user3285962
  • 41
  • 1
  • 5
  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Konrad Dec 15 '22 at 15:49
  • You'll want to use the built in router in NextJS for client-side transitions. Instead of `window.location.assign` import the [useRouter](https://nextjs.org/docs/api-reference/next/router) hook and use: `router.push("/admin/blog-edit")`. – jme11 Dec 15 '22 at 17:52
  • @jme11 You don't know how happy you've made me, that worked! I was looking for the solution in the wrong place. – user3285962 Dec 16 '22 at 20:03
  • @Konrad thank you that article was informative but not the solution in this case. – user3285962 Dec 16 '22 at 20:03
  • You run `console.log` just after setting the state, it won't have new values. New values will be present in state after rerender – Konrad Dec 16 '22 at 20:07

0 Answers0