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>
)
}