Answers for "TypeError: Cannot read property 'map' of undefined"

0

TypeError: Cannot read property 'map' of undefined

function MyComponent() {
  const [data, setData] = useState([]);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    setLoading(true);
    fetch('/api/data')
      .then((res) => res.json())
      .then((data) => {
        setData(data);
      })
      .catch((err) => {
        console.log(err);
      })
      .finally(() => {
        setLoading(false);
      });
  }, []);

  if (loading) {
    return <p>Data is loading...</p>;
  }

  return (
    <ul>
      {data.map((item) => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
}
Posted by: Guest on July-15-2021

Code answers related to "TypeError: Cannot read property 'map' of undefined"

Browse Popular Code Answers by Language