Search code examples
javascriptarraysreactjsreact-reduxuse-effect

nested array object property return undefined typeError in react redux


i want to show the post detail in frontend. my api is showing the postdetail like below captured in postman:

"message": "Posts fetched successfully!",
    "posts": {
        "_id": "61f05f676793d49f466e7aaa",
        "title": "Liberal Arts Student Sample",
        "content": "The three-page.",
        "creator": {
            "_id": "61cd99efa0b8d616a7a53ce1",
            "createdAt": "2021-12-30T11:37:19.041Z",
            "updatedAt": "2022-01-06T14:35:48.801Z",
            "__v": 0,
            "bio": "user bio",
            "name": "username"
        },
        "Comments": [],
        "created": "2022-01-25T20:36:55.095Z",
        "createdAt": "2022-01-25T20:36:55.096Z",
        "updatedAt": "2022-01-25T20:36:55.096Z",
        "__v": 0
    }
}

i want to exhibit this post detail in frontend and here is the code:

export default function PostDetail() {
    const { postId } = useParams();
    const post = useSelector((state) => state.post)
    const dispatch = useDispatch();
    const { title, content,creator, created } = post;
    const fetchPostDetail = async (id) => {
        const response = await axios.get(`http://localhost:5000/api/articles/post/${id}`, { post })
            .catch(err => {
                console.log(err);
            })
        dispatch(selectedPost(response.data.posts));
              }

    useEffect(() => {
        fetchPostDetail(postId)
    }, [])


    return (
        <div>
            <h1>Post Detail</h1>
            <div>
                <h2>{title}</h2>
                <i>posted in {created}</i>
                 <li>Created by {creator.map((m,i)=>(
<b key={i}>{m.name}</b>
                 ))}</li> 
                <p>{content}</p>
            </div>
        </div>
    );
}

There are three errors:

  1. Uncaught TypeError: creator is undefined
  2. The above error occurred in the component:
  3. Uncaught TypeError: creator is undefined

if i mute the

  • Created by {creator.map((m,i)=>( {m.name} ))}
  • then it shows the post detail without post author name. but i want to show the author name.

    how can i solve that? thank you in advance


    Solution

  • For the first time when the component will mount, the value of the creator will be undefined. You need to add a check before getting the nested value.

    <div>
      <h1>Post Detail </h1>
      <div>
        <h2>{title} </h2>
        <i> posted in {created} </i>
        {creator && <li> Created by :{creator.name}</li>}
        <p> {content} </p>
      </div>
    </div>
    

    Note: One thing more, Creator is not an array. it is an Object. So you cant map the object. In case it is an array, You have to make above check in that case too.