skip to Main Content

Data won’t load until I refresh the page. I believe the issue is state management but I can’t seem to make it work. Any help is greatly appreciated!

When a user signs up for an account, they log into the session and all users posts are supposed to be rendered. However, in my case, it’s not rendering until I refresh the page.

client/src/context/ContentContext.js

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 }

client/src/posts/PostDetail.js

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;

2

Answers


  1. i think that should be okey :

     import React, { useContext, useEffect, useState } from "react";
    import { ErrorContext } from "./ErrorContext";
    import { AuthContext } from "./AuthContext"; 
    
    const ContentProvider = ({ children }) => {
      const { setErrors } = useContext(ErrorContext);
      const { isLoggedIn } = useContext(AuthContext); 
      const [contents, setContents] = useState([]);
      const [loading, setLoading] = useState(true); 
    
      useEffect(() => {
        if (isLoggedIn) {
          fetch('/posts')
            .then((resp) => {
              if (resp.ok) {
                resp.json().then((data) => {
                  setContents(data);
                  setLoading(false); 
                });
              } else {
                setLoading(false); 
                setErrors("Err");
              }
            })
            .catch((error) => {
              setLoading(false); 
              setErrors(error);
            });
        }
      }, [isLoggedIn, setErrors]);
    
      return (
        <ContentContext.Provider value={{ contents, setLoading }}>
          {loading ? <p>Loading...</p> : children}
        </ContentContext.Provider>
      );
    };
    
    export { ContentProvider };
    
    Login or Signup to reply.
  2. File: client/src/posts/PostDetail.js

    import { useContext, useEffect, useState } from "react";
    
    function PostDetail() {
      const { setErrors } = useContext(ErrorContext);
      const { user } = useContext(UserContext);
      const { contents, deletePost } = useContext(ContentContext);
      const [post, setPost] = useState({});
      const postId = parseInt(useParams().id);
    
      useEffect(() => {
        if (contents?.length) {
          const content = contents.find((c) => c.id === postId);
          setPost(content);
        }
      }, [contents]);
    
      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;
    
    

    Try this code And let me know if it helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search