How to Handle Text API Response using Fetch in React Native
We get API responses mostly in JSON format. It’s due to the simplicity and popularity of JSON. Sometimes, developers prefer to give API responses in raw text. In this blog post, let’s check how to handle text responses using Fetch in react native.
React Native provides Fetch API for our networking needs. Fetch returns promise so that it automatically works asynchronously. In normal cases, that is when the response is in JSON, then you use Fetch as given below.
const getMoviesFromApi = () => {
return fetch('https://reactnative.dev/movies.json')
.then((response) => response.json())
.then((json) => {
return json.movies;
})
.catch((error) => {
console.error(error);
});
};
But using the above code for text response cause error. In that case you have to use response.text() instead of response.json(). See the code snippet given below.
fetch('https://example/API',
{
method: 'POST',
},
)
.then(response => response.text())
.then(response => {
console.log(response);
})
.catch(error => {
console.error(error);
});
That’s how you handle text response from the server side using fetch in react native.
I hope this short react native fetch tutorial is helpful for you.