❗️Error/오류를 해결하자!

data.map is not a function

hellohailie 2022. 8. 18. 18:03

 

✔️ 에러 코드

Uncaught TypeError: data.map is not a function

 

 

✔️ 에러가 나온 이유

이 오류의 원인은 다양한데, 이번에는 운좋게 구글링을 통해서 바로 해결할 수 있었다. 이번에는 이런 식으로 array인지 확인해서 이게 true 이면 map을 사용하는 식으로 했다.

{Array.isArray(data) ? data.map((item) ⇒ …

 

 

👇에러코드 👇

import { useEffect, useState } from "react";
import styled from "styled-components";

const Section = styled.div`
  border: 1px solid black;
  margin: 5px;
  padding: 5px;
  display: flex;
  justify-content: space-between;
`;

const BucketListMain = () => {
  const [data, setData] = useState({});

  useEffect(() => {
    let isMounted = true;
    fetch("http://localhost:3001/data/")
      .then((response) => response.json())
      .then((item) => setData(item))
      .catch((err) => {
        console.log(err);
      });
    // if (isMounted) {
    //   setData(result);
    // }
  }, ["http://localhost:3001/data/"]);

  return (
    <Section>
      {data.map((item) => {
        return (
          <li key={item.id} className='data-list'>
            <div className='city'>{item.city}</div>
            <div className='doing'>{item.doing}</div>
            <img className='photo' src={item.photo} alt='' />
          </li>
        );
      })}
    </Section>
  );
};
export default BucketListMain;

👇에러  수정 코드 👇

import { useEffect, useState } from "react";
import styled from "styled-components";

const Section = styled.div`
  border: 1px solid black;
  margin: 5px;
  padding: 5px;
  display: flex;
  justify-content: space-between;
`;

const BucketListMain = () => {
  const [data, setData] = useState({});

  useEffect(() => {
    let isMounted = true;
    fetch("http://localhost:3001/data/")
      .then((response) => response.json())
      .then((item) => setData(item))
      .catch((err) => {
        console.log(err);
      });
    // if (isMounted) {
    //   setData(result);
    // }
  }, ["http://localhost:3001/data/"]);

  return (
    <Section>
      {Array.isArray(data)
        ? data.map((item) => {
            return (
              <li key={item.id} className='data-list'>
                <div className='city'>{item.city}</div>
                <div className='doing'>{item.doing}</div>
                <img className='photo' src={item.photo} alt='' />
              </li>
            );
          })
        : null}
    </Section>
  );
};
export default BucketListMain;

 

 

참고)

 

https://bobbyhadz.com/blog/javascript-map-is-not-a-function

 

Solve - map is not a function Error in JavaScript | bobbyhadz

The "TypeError map is not a function" occurs when we call the `map()` method on an object that is not an array. To solve the error, `console.log` the value you're calling the `map()` method on and make sure to only call the `map` method on valid arrays.

bobbyhadz.com

 

 

 

 

😃 잘못된 개념 전달이 있다면 댓글 부탁드립니다. 저의 성장에 큰 도움이 됩니다🤓