Search code examples
jsonreactjsfetchresponseparse-error

Fetch fails to receieve large responses


I'm trying to fetch in react-native(js), but the response is being corrupted many times, especially for larger data!

Response is an array, for array size < 5 fetch is usually working, for array size > 20 fetch is almost never working, giving the following error:

[Unhandled promise rejection: SyntaxError: JSON Parse error: Expected ']']

This is the code used to fetch:

        fetch(url)
        .then(response => {
            if(response.status!==200){alert('Something went wrong, please try again later');return null}
            return response.json()
        })
        .then(response => {
            if (response == null){return}
            console.log(response)
        })

The error occurs at the 'return response.json()' line.

Please help! Thanks.


Solution

  • You may need to check the json that you are sending back from the server. The error is occurring to malformed json. However it also may be how you are formatting your fetch.

    Here is some code for getting the json from an api. This a pretty good example from the article by matt gaunt, https://developers.google.com/web/updates/2015/03/introduction-to-fetch#:~:text=The%20response%20of%20a%20fetch,the%20stream%20will%20happen%20asynchronously.

    fetch('./api/some.json')
      .then(
        function(response) {
          if (response.status !== 200) {
            console.log('Looks like there was a problem. Status Code: ' +
              response.status);
            return;
          }
    
          // Examine the text in the response
          response.json().then(function(data) {
            console.log(data);
          });
        }
      )
      .catch(function(err) {
        console.log('Fetch Error :-S', err);
      });