Fetch Method:
Here's an example of how to use fetch()
for both GET and POST requests in React Native:
GET Request:
javascriptCopy codefetch('https://example.com/api/data')
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
This GET request is similar to the previous example, where we are fetching data from the API endpoint and parsing the response as JSON. You can replace the URL with your own API endpoint.
POST Request:
javascriptCopy codeconst requestData = {
name: 'John',
email: 'john@example.com'
};
fetch('https://example.com/api/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(requestData)
})
.then((response) => response.json())
.then((data) => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
For a POST request, we pass an additional argument to the fetch()
function, an options object that includes the method, headers, and body of the request. In this example, we are sending a JSON object with a name and email property in the request body.
The method
property specifies the HTTP method to use for the request, in this case POST. The headers
property specifies the content type of the request, which is JSON in this example. The body
property contains the data to be sent in the request, which is converted to a JSON string using JSON.stringify()
.
Once we receive a response, we parse the response as JSON and log the data to the console. If an error occurs during the fetch, we catch it and log the error to the console.
Axios Method:
GET Request:
javascriptCopy codeimport axios from 'axios';
axios.get('https://example.com/api/data')
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
This GET request is similar to the previous example, where we are fetching data from the API endpoint and logging the response data to the console. You can replace the URL with your own API endpoint.
POST Request:
javascriptCopy codeimport axios from 'axios';
const requestData = {
name: 'John',
email: 'john@example.com'
};
axios.post('https://example.com/api/data', requestData)
.then((response) => {
console.log(response.data);
})
.catch((error) => {
console.error(error);
});
For a POST request, we use the axios.post
()
method, passing the URL of the API endpoint and the data to be sent in the request as an object. In this example, we are sending a JSON object with a name and email property in the request body.
Once we receive a response, we log the response data to the console. If an error occurs during the request, we catch it and log the error to the console. Note that Axios automatically sets the content type of the request to JSON.