jineecode

useEffect hooks with axios cannot read property of undefined 본문

JS/react

useEffect hooks with axios cannot read property of undefined

지니코딩 2021. 5. 13. 17:23

TypeError: Cannot read property 'name' of undefined

 

상황: axios로 API를 불러오고자 할 때, API를 불러오기도 전에 렌더링 되어 undefined를 보게 되는 상태

 

import React, { useState, useEffect } from "react";
import axios from "axios";

const Emote = ({ match, history }) => {
  let [emote, setEmote] = useState([]);
  useEffect(() => {
    axios
      .get(`https://ffxivcollect.com/api/emotes/${match.params.id}`)
      .then((res) => {
        console.log(res.data);
        setEmote(res.data);
        console.log(res.data.category.name);
      })
      .catch((e) => {
        console.log("실패");
      });
  }, []);

  return (
    <main>
      <div className="emote-card">
        <div className="card-head">
          <div className="img-box">
            <img src={emote.icon} alt="#" />
          </div>
          <h3>{emote.id}</h3>
          <h3>{emote.name}</h3>
        </div>
        <div className="card-body lists">
          <div className="emote-info list">
            <ul>
              <li>
                <span className="no">카테고리: </span>
                {emote.category.name}
              </li>
              <li>
                <span className="no">패치: </span>
                {emote.patch}
              </li>
              <li>
                <span className="no">커맨드: </span>
                {emote.command}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </main>
  );
};

export default Emote;

분명히 데이터는 존재하지만,

 

타입에러가 뜨며 렌더링 되지 못하는 상황이다.

 

 

해결: 렌더링을 조건부로 주면 해결이 가능하다.

useState에 ( )가 아닌 null로 넣어주고 렌더링에 조건문을 넣어주면 에러없이 렌더링 된다.

const Emote = ({ match, history }) => {
  let [emote, setEmote] = useState(null);
  
  useEffect(() => {
    axios
      .get(`https://ffxivcollect.com/api/emotes/${match.params.id}`)
      .then((res) => {
        setEmote(res.data);
      })
      .catch((e) => {
        console.log("실패");
      });
  }, []);

  if (emote) {
    return (
      <main>
        <div className="emote-card">
          <div className="card-head">
            <div className="img-box">
              <img src={emote.icon} alt="#" />
            </div>
            <h3>{emote.id}</h3>
            <h3>{emote.name}</h3>
          </div>
          <div className="card-body lists">
            <div className="emote-info list">
              <ul>
                <li>
                  <span className="no">카테고리: </span>
                  {emote.category.name}
                </li>
                <li>
                  <span className="no">패치: </span>
                  {emote.patch}
                </li>
                <li>
                  <span className="no">커맨드: </span>
                  {emote.command}
                </li>
              </ul>
            </div>
          </div>
        </div>
      </main>
    );
  } else {
    return null;
  }
};

export default Emote;

 

https://stackoverflow.com/questions/62207658/react-useeffect-hooks-with-axios-cannot-read-property-of-undefined

 

react useEffect hooks with axios cannot read property of undefined

This is based on exercise 2.14 of this course https://fullstackopen.com/en/part2/getting_data_from_server. The user can select a country, then the weather information for that country's capital wi...

stackoverflow.com

 

'JS > react' 카테고리의 다른 글

React Native 기본 원리  (0) 2021.06.19
import, export  (0) 2021.05.28
Using target=_blank without rel=noopener noreferrer is a security risk  (0) 2021.05.10
useEffect 사용  (0) 2021.05.02
react-router-dom 다루기  (0) 2021.04.30
Comments