1

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

2
  • Did you check response from server? Is it setting right in data? Commented Jul 14, 2020 at 10:56
  • If api.get returns a promise of the above JS object, shouldn't it be const listResult = res.data? Otherwise you get res.data.data Commented Jul 14, 2020 at 11:01

2 Answers 2

1

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>
  )
})}
Sign up to request clarification or add additional context in comments.

Comments

1

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(....

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.