Search code examples
jsonreactjsapireact-nativemap-function

Unhandled promise rejection Error: Cannot read property 'json' of undefined


answers.map((answer, index) => {
  answer_text = answer.answer_text;
  id = answer.id;
  return fetch(BASE_URL + url, {
    method: 'PUT',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Token token=' + token
    },
    body: JSON.stringify({
      question: {
        answers_attributes: {
          '0': {
            answer_text: answer_text,
            id: id
          }
        }
      }
    })
  });
})

I used map function so that on every map it should go to JSON.stringify and assign the values. But I got error "Unhandled promise rejection TypeError: Cannot read property 'json' of undefined". please suggest me any solution.

Thanks in advance.


Solution

  • Here you are creating an array of fetch promises, we need more info about how you handle these promises after that, i suppose you're trying somewhere to get a response from these promises using .then(res => res.json()) but your server response is not in json format.

    To handle a fetch promise rejection you need to do this:

    fetch(smth)
    .catch(error => //handle the error e.g. console.log(error))
    

    To see if there's something wrong in your request json body you can log it server side or log it before sending, you can also log the server response, try this to identify what's wrong:

    answers.map((answer, index) => {
      answer_text = answer.answer_text;
      id = answer.id;
      const body = JSON.stringify({
          question: {
            answers_attributes: {
              '0': {
                answer_text: answer_text,
                id: id
              } }
          }
        })
    console.log('Json body request :', body);
      return fetch(BASE_URL + url, {
        method: 'POST',
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
          'Authorization': 'Token token=' + token
        },
        body
      }).then(res => {
        console.log('server response :', res);
        return res;
      }).catch(err => console.log('Fetch error :', err));
     })
    

    I recommend using an app like Postman to test the responses from your api server (easier & faster to debug request/responses from an API)

    Edit: I also think you want to do a POST request instead of PUT.