1

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

7
  • Remove the first article. from article.articles.pk_article_nr Commented Dec 12, 2021 at 17:27
  • Make sure you use optional chaining like article?.articles?.pk_article_nr. It will help you to avoid some error. Commented Dec 12, 2021 at 17:31
  • Hey @Grumpy, thanks for your advice. Now it is showing Failed to compile src\components\ArticleDetail.js Line 29:11: 'articles' is not defined no-undef Search for the keywords to learn more about each error. Greetings, Max Commented Dec 12, 2021 at 17:32
  • Does this answer your question? React returns "Cannot read property "name" of undefined." (Fetch API) Commented Dec 12, 2021 at 17:32
  • @max, my bad, didnt look right at the source. Commented Dec 12, 2021 at 17:34

1 Answer 1

8

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

Sign up to request clarification or add additional context in comments.

7 Comments

Hey @Reza Mohabbat, now it's working. Thank you. I will try to understand why. Cheers, Max
@max Good luck.
@RezaMohabbat can you add some more detail to your answer to indicate why this would solve the specific issue (I'm aware of why myself, but for future readers it might be helpful).
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
@Dr_Derp Yes, Sure!
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.