how to foreach/map array inside objects on react hooks?

I have a json from an API like this

"data": {
    "total_question": 2,
    "correct_answer": "1/2",
    "correct_percentage": 50,
    "details": [
        {
            "question_id": 1,
            "question": "test questioner 1",
            "choice": "choice 1.1",
            "result": "correct",
            "percentage_choice": 100
        },
        {
            "question_id": 2,
            "question": "test questioner 2",
            "choice": "choise 2.3",
            "result": "incorrect",
            "percentage_choice": 100
        }
    ]
}

then I will enter the response of the API into a state

const [data, setData] = useState({})

this is a fetch for data

const fetchResult = () => {
    api.get(`api/questionnaire/getResult?voteId=${id}`)
      .then(res => {
        const { data: listResult } = res.data
        setLoading(false)
        setData(listResult)
      })
      .catch(err => console.log('error'))
  }
  useEffect(() => {
    fetchResult()
  }, [])

this is the result of the response API being displayed

<Card>
  <Card.Body>
    {Object.keys(data.details).map(item => {
      return (
        <Col key={item.question_id} xs={12} className='mb-3'>
          <h5>{item.question}</h5>
          <ProgressBar 
            variant='danger' 
            now={item.percentage_choice} 
            label={`${item.percentage_choice}%`} 
          />
        </Col>
      )
    })}
   <Col xs={12}>
     <h5>Total question: {data.total_question}</h5>
   </Col>
  </Card.Body>
</Card>

how to get details and map it? I always get the following message: TypeError: Cannot convert undefined or null to object

Upvotes: 1

Views: 2202

Answers (2)

Den Kison
Den Kison

Reputation: 1084

Looks like data.details -> Object.keys(data.details) is already array and you don't need to get keys from it. Try to use map directly data.details.map(....

Upvotes: 1

aravind_reddy
aravind_reddy

Reputation: 5466

you need to do check if the object/array you are trying to access is valid or not first then you can directly map over the array(data.details)... something like this:

{data.details && data.details.map(item => {
  return (
    <Col key={item.question_id} xs={12} className='mb-3'>
      <h5>{item.question}</h5>
      <ProgressBar 
        variant='danger' 
        now={item.percentage_choice} 
        label={`${item.percentage_choice}%`} 
      />
    </Col>
  )
})}

Upvotes: 1

Related Questions