Home > OS >  How can I access property in nested array?
How can I access property in nested array?

Time:12-17

I have made an API with quiz questions which I have been able to fetch and now I'm trying to render a single property ("clue1") from the "questions" array.

This is my code so far:

export const SingleClue = () => {
  const [questions, setQuestions] = useState({})

  const fetchData = () => {
    fetch('https://final-project-api-veooltntuq-lz.a.run.app/questions')
      .then((response) => {
        return response.json()
      })
      .then((data) => {
        setQuestions(data)
      })
  }

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

  return (
    <div>
      <div>
        {questions.map((question) => (
          <div key={id}>
            {question.questions.map((clue) => (
              <div key={id}>
                <h2>{clue.clue1}</h2>
              </div>
            ))}
          </div>
        ))}
      </div>

    </div>
  )
}

I've tried with different types of mapping over it, but nothing seems to work. What am I missing?

CodePudding user response:

import { useState, useEffect } from 'react';
import * as React from 'react';

const App: React.FC = () => {
  const [questions, setQuestions] = useState([]);//FIX 1 -> make default state array

  const fetchData = () => {
    fetch('https://final-project-api-veooltntuq-lz.a.run.app/questions')
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        console.log(data);
        setQuestions(data.questions);//FIX 2-> set response.questions as state
      });
  };

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

  return (
    <div>
      <div>
        {questions.map((question, id) => (
          <div key={id}>
            //FIX 3 -> No need to iterate here.
              <div key={id}>
                <h2>{question.clue1}</h2>
              </div>
            
          </div>
        ))}
      </div>
    </div>
  );
};

export default App;

CodePudding user response:

You could simply access the property directly, like this:

return (
  <div>
    <h2>{questions.clue1}</h2>
  </div>
)

Or, if you want to render multiple properties from the "questions" array, you can use the map function to iterate over the array and render each element. Like this:

return (
  <div>
    {questions.map((question) => (
      <div key={question.id}>
        <h2>{question.clue1}</h2>
        <p>{question.clue2}</p>
      </div>
    ))}
  </div>
)

This will render the "clue1" and "clue2" properties for each element in the "questions" array.

  • Related