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

365
Visualizações
React JS fetching data (error: Cannot read properties of undefined)

i am just trying to learn JavaScript. I have to create a web application for school. Now i am trying to fetch data from a self written api. The backend is written with express, the frontend with JavaScript. I have got a overview page, where all products are shown. After clicking on the detail button, the user should be able to view the details of the selected product. For this i use this code.

import React, { useState, useEffect } from "react";
import "./Articles.css";

function ArticleDetail({ match }) {
  useEffect(() => {
    fetchArticle();
  }, []);

  const [article, setArticle] = useState([]);

  async function fetchArticle() {
    try {
      const response = await fetch(
        `http://localhost:8000/api/articles/${match.params.id}`
      );
      const article = await response.json();
      //console.log(data.results);
      console.log(article);
      setArticle(article);
      return article;
    } catch (error) {
      console.error(error);
    }
  }

  return (
    <div>
      <p>TEST</p>
      <p>{article.articles.pk_article_nr}</p>
      <p>TEST</p>
    </div>
  );
}

export default ArticleDetail;

If i run this code and don't refresh the page by myself, the correct value (pk_article_nr) is shown. If i refresh the browser manually there is this error

TypeError: Cannot read properties of undefined (reading 'pk_article_nr')

This data are shown in the console:

{articles: {…}}
  articles:
    article_description: "lorem ipsum"
    article_expiretimestamp: "2022-01-15 18:52:27"
    article_picture: null
    article_timestamp: "2022-01-15 18:37:27"
    article_title: "Test 4"
    bid_amount: 80
    fk_article_nr: 4
    fk_user_userid: null
    pk_article_nr: 4
    pk_bid_id: 8`

Could you please help me? I haven't found anything that helps me. Maybe i just searched for the wrong thing.

Thank you, Max

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

0

You should change

<p>{article.articles.pk_article_nr}</p>

to

<p>{article?.articles?.pk_article_nr}</p>

Reason for this to happen:

React wants to access the property before mounting, while the property has not yet received any content

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