Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Fetch nested array React

I am learning React but having problems with fetching nested arrays from my API. I am trying to render an array as buttons. At first the code works but on refreshing the webpage I get a blank page and this error in the console: "Uncaught TypeError: item.options is undefined".

  let { id } = useParams();
  //console.log(id);
  //kalla pĂĄ fetchItem
  useEffect(() => {
    getMovie();
  }, []);
  //hämta enskild
  const [item, setItem] = useState([]);

  const getMovie = async () => {
    const fetchItem = await fetch(`http://localhost:5000/api/movies/id=${id}`);

    const item = await fetchItem.json();
    setItem(item);
    console.log(item);
  };

  //hämta, map för att det är array
  return (
    <div className="App">
      <h1>Hello</h1>
      <h2>Question: {item.description}</h2>
      {item.options.map((c) => (
        <button key={c.text}>{c.text}</button>
      ))}
    </div>
  );

This is my mongoose schema

const MovieSchema = mongoose.Schema(
  {
    category: { type: String, required: true },
    description: { type: String, required: true },
    image: {
      type: String,
      required: false,
    },
    options: [
      {
        text: {
          type: String,
          required: true,
        },
        is_correct: {
          type: Boolean,
          required: true,
          default: false,
        },
        image: {
          type: String,
          required: false,
        },
      },
    ],
  },
  { collection: "movies" }
);

// Big noob, thanks for helping

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your initial state is wrong, as the empty array [] has no property options that could be mapped. Instead try:

const [item, setItem] = useState({options: []});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading