skip to Main Content

I keep getting error saying the property I’m trying to loop over is undefined. However is I paste the same data in as a variable it works. Also the console.log shows the data is there. This is a component that gets pulled in with Hash Router. What am I doing wrong?

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

export default function Icons() {


  const [icons, setIcons] = useState([]);
  useEffect(() => {
    fetch(
      "https://.....can't show full url....json/icon-json.json"
    )
      .then(response => response.json())
      .then(data => {
        console.log(data);
        setIcons(data);
      })
      .catch(err => {
        console.log(err.message);
      });
  }, []);

  console.log(icons);

  return (
    <div>
      <h2>Icons</h2>
      {icons.children.map(icon => {
        return (
          <div key={icon.path} className={"iconDiv"}>
            <img src={icon.path} alt="" width="24px" />
            <p>{icon.name}</p>
            <button
              onClick={() => navigator.clipboard.writeText(icon.path)}
              className="clipboardButton"
            >
              <img
                src="https://..can't show full url..../icons/copy_neutral.png"
                alt=""
                width="12px"
              />
            </button>
          </div>
        );
      })}
    </div>
  );
}

2

Answers


  1. This is because you are doing icons is an array, but you are trying to access it as an object.

    Try icons[0].children.map for example.

    Login or Signup to reply.
  2. When you do this:

    const [icons, setIcons] = useState([]);
    

    icons is an empty array [].

    Then you try to do this icons.children.map where icons.children is undefined, thus the error.

    You probably want to do icons.map instead.

    In case the data of your fetch returns a nested objects with a children field, you probably want to set the icons properly:

    setIcons(data.children)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search