K
K
Kipsy2021-10-14 15:28:00
React
Kipsy, 2021-10-14 15:28:00

Why is there an error with map in react?

Good afternoon. Please tell me why in the code when you try to go through map, an error occurs in the block with map exactly.
'Cannot read properties of undefined (reading 'map')'
Am I wrong?

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

export default function App() {
  const [load, setLoading] = useState(true);
  const [data, setData] = useState();
  useEffect(() => {
    const fetchData = async() => {
      const res = await fetch('https://jsonplaceholder.typicode.com/comments');
      const data = await res.json()
      setData(data)
    }
    fetchData()
  }, [load])

  console.log(data)

  return (
    <div className="App">
      <h1>Hello Code</h1>
      {data.map((item, idx) => (
        <div key={idx}>
          <h2>{item.name}</h2>
        </div>
      ))}
    </div>
  );
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Aetae, 2021-10-14
@Kipsi

const [data, setData] = useState([]);
Now in order you have this:
1.

const [data, setData] = useState(); // data === undefined

2. 3. 4. Numbers flow through wires... 5. 6.data.map((item, idx) => ( // error
data.map((item, idx) => ( // ok

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question