Search code examples
javascriptreactjsredux

React component getting rendered multiple times


feedPosts array is getting iterated for 3 times where posts are fetched from the store and though i have added key prop to the postComponent i am getting error to add a key

const Home = ()=>{ 
    const navigate = useNavigate();
    const dispatch = useDispatch();
    const authToken = Cookies.get("jwtToken");
    const feedPosts = useSelector(state => state.feedPosts.posts);
    useEffect(()=>{
      axios.get("http://localhost:8080/posts",{
    headers:{
        'authorization': authToken
    }}).then((posts)=>{
      dispatch(setFeedPosts({posts: posts.data}))
    })
    },[]);
    return(
      <div className="homepage">
        <div className="post-container">
          {feedPosts.map((post)=>
            <PostComponent key={post.id}
            firstName={post.firstName} 
            lastName={post.lastName} 
            userId={post.userId}
            content={post.content}
            />
          )}
        </div>
     </div> 
    )
}

Solution

  • const Home = () => {
    const dispatch = useDispatch();
    const feedPosts = useSelector((state) => state.feedPosts.posts);
    
    useEffect(() => {
      const fetchData = async () => {
        if(feedPosts.length) return
        try {
          const response = await axios.get('http://localhost:8080/posts', {
            headers: {
              Authorization:authToken,
            },
          });
          dispatch(setFeedPosts({ posts: response.data }));
        } catch (error) {
          console.error('Error fetching posts:', error);
        }
      };
    
      fetchData();
    }, []);
    
    return (
      <div className="homepage">
        <div className="post-container">
          {feedPosts.map((post) => (
            <PostComponent
              key={post.id}
              firstName={post.firstName}
              lastName={post.lastName}
              userId={post.userId}
              content={post.content}
            />
          ))}
        </div>
      </div>
    );
    

    }; export default Home; make sure the post id's are unique