samedi 3 avril 2021

TypeError: Cannot read property 'map' of undefined React.Js after changng from 1 comppnent to 2 parent, child components

I had a component which fetched and rendered data from API and it was working. But for some function I had to convert this component 2 separate components (Parent and Child). Since doing that it's not working 'TypeError: Cannot read property 'map' of undefined', I m getting this error. I need it working only this way (parent, child structure). How can I do that ?

Here's Parent Component:-

import React, { useEffect, useState } from "react";
import axios from "axios";
import PostListItem from "./PostListItem";

const PostList = () => {
  useEffect(() => {
    getPost();
  }, []);

  const [posts, setPosts] = useState([]);

  const getPost = async () => {
    const res = await axios.get("http://localhost:5000/posts/");
    setPosts(res.data);
  };

  const renderList = () => {
    return posts.map((post) => {
      return <PostListItem post={post} />;
    });
  };

  return <div>{renderList()}</div>;
};

export default PostList;

Here's Child Element:-

    import React from "react";
    
    const PostListComponent = (post) => {
      const renderDate = (dateString) => {
        const monthNames = [
          "January",
          "February",
          "March",
          .
.
.
.
        ];
        const date = new Date(dateString);
        return `${
          monthNames[date.getMonth()]
        } ${date.getDate()}, ${date.getFullYear()}`;
      };
    
      const renderTags = (tags) => {
        return tags.map((tag, index) => {
          index = index + 1;
          return <span key={index}>{tag}</span>;
        });
      };
      return (
        <button key={post._id}>
          <h3>{post.title}</h3>
          <span>{renderDate(post.createdAt)}</span>
          <div>{renderTags(post.tags)}</div>
        </button>
      );
    };
    
    export default PostListComponent;

Here's error:-

TypeError: Cannot read property 'map' of undefined
  25 | const renderTags = (tags) => {
  26 |   return tags.map((tag, index) => {
  27 |     index = index + 1;
> 28 |     return <span key={index}>{tag}</span>;
     | ^  29 |   });
  30 | };
  



Aucun commentaire:

Enregistrer un commentaire