skip to Main Content

After executing my React code, I gotthe following error message in the browser console: "TypeError: Cannot read property ‘map’ of undefined". here is my code


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

  useEffect(() => {
    fetchData();
  }, []);

  const fetchData = async () => {
    const response = await fetch('https://api.example.com/data');
    const jsonData = await response.json();
    setData(jsonData);
  };

  return (
    <div>
      {data.map((item) => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
};

export default MyComponent;

2

Answers


  1. I recommend that you use try…catch to handle possible errors in your request, so your app won’t break. Like this:

    const fetchData = async () => {
      try {
        const response = await fetch('https://api.example.com/data');
        const jsonData = await response.json();
        setData(jsonData);
      }
      catch (error) {
        // If the request returns an error...
        setData([]);
      }
    }
    

    If the error persists, probably your request has no error but is not returning anything (undefined).

    Login or Signup to reply.
  2. **You need to check first data should be defined when component renders **
    
     const MyComponent = () => {
        const [data, setData] = useState([]);
    
     useEffect(() => {
       fetchData();
     }, []);
    
     const fetchData = async () => {
      const response = await fetch('https://api.example.com/data');
      const jsonData = await response.json();
      setData(jsonData);
     };
    
     return (
        <div>
          {data && data.length?.map((item) => (
            <div key={item.id}>{item.name}</div>
          ))}
        </div>
      );
    };
    
    export default MyComponent;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search