Home > Software engineering >  Fetch nested array React
Fetch nested array React

Time:12-21

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

CodePudding user response:

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

const [item, setItem] = useState({options: []});
  • Related