React - content not loading until refreshed - state management issue
<p>The data doesn't load until I refresh the page. I think the problem is state management but can't seem to get it to work. Any help is greatly appreciated! </p>
<p>When a user registers an account and they log into the session, all of the user's posts should be rendered. However, in my case it doesn't render until I refresh the page. </p>
<p>client/src/context/ContentContext.js</p>
<pre class="brush:php;toolbar:false;">import { createContext, useContext, useEffect, useState } from "react";
import { ErrorContext } from "./ErrorContext";
const ContentContext = createContext({});
const ContentProvider = ({children}) => {
const { setErrors } = useContext(ErrorContext);
const [contents, setContents] = useState([]);
useEffect(() => {
fetch('/posts')
.then(resp => {
if (resp.ok) {
resp.json().then(data => {
setContents(data);
});
}
})
.catch(errors => {
setErrors(errors);
});
}, [setErrors])
const addPost = (newPost) => {
setContents([...contents, newPost]);
}
const editPost = (newPost) => {
const updatedContentList = contents.map(post => {
if (newPost.id === post.id) {
return newPost
} else {
return post;
}
});
setContents(updatedContentList);
}
const deletePost = (id) => {
const updatedContentList = contents.filter(post => post.id !== id)
setContents(updatedContentList);
}
return (
<ContentContext.Provider value={{ contents, addPost, editPost, deletePost }}>{children}</ContentContext.Provider>
)
}
export { ContentContext, ContentProvider }</pre>
<p>client/src/posts/PostDetail.js</p>
<pre class="brush:php;toolbar:false;">import { useContext, useEffect, useState } from "react";
function PostDetail () {
const { setErrors } = useContext(ErrorContext);
const { user } = useContext(UserContext);
const { contents, deletePost } = useContext(ContentContext);
const postId = parseInt(useParams().id);
const post = contents.find(post => post.id === postId);
useEffect(() => {
fetch(`/posts/${post.id}/likes`)
.then(resp => resp.json())
.then(data => {
setLiked(data.liked);
})
.catch(error => {
setErrors(error)
})
}, [post.id, setErrors])
}
export default PostDetail;</pre>
<p><br /></p>