Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading