Skip to content
Advertisement

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement