Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

40
Visualizações
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

    about 4 years ago · Juan Pablo Isaza
    3 Respostas
    Responde à pergunta

    0

    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.

    about 4 years ago · Juan Pablo Isaza Relatório

    0

    make sure the post object contains the "creator" key, and you don't need map() if the state looks exactly like the API response. If you could show how the state looks that will reveal more of the issue.

    about 4 years ago · Juan Pablo Isaza Relatório

    0

    Here, creator is an Object. Whereas .map function is for Array. To map an Object you can check: map function for objects (instead of arrays)

    about 4 years ago · Juan Pablo Isaza Relatório
    Responde à pergunta
    Encontrar trabalhos remotos

    Descubra a nova forma de encontrar um emprego!

    melhores empregos
    Principais categorias de trabalho
    Empresas
    Postar vaga Preços Comercial
    Jurídico
    Termos e Condições Política de privacidade
    © 2026 PeakU Inc. All Rights Reserved.
    Andres GPT
    Recomende algumas ofertas para mim
    Preciso de ajuda