To send data with a GET request using the fetch API in React, you can use the following steps:
First, create a function that will send the GET request. You can do this by using the fetch function, which takes the URL of the endpoint as its first argument and an options object as its second argument.
In the options object, set the method property to "GET" to specify that this is a GET request. You can also set any other properties you need, such as headers or mode.
To include query parameters in the request, you can append them to the URL as a query string. For example, if you want to include a parameter called name with the value "John", you could append "?name=John" to the end of the URL.
If you want to include multiple query parameters, you can separate them with an & symbol. For example, "?name=John&age=30".
To send the request, you can call the fetch function and chain a .then method to the end of it. This .then method will be called with the response from the server as its argument. You can use this response to extract the data you need or to check for errors.
Here is an example of how you might use the fetch function to send a GET request with query parameters in a React component:
import React, { useState, useEffect } from 'react';
function MyComponent() {
const [data, setData] = useState(null);
useEffect(() => {
const fetchData = async () => {
const response = await fetch(
'https://my-api.com/endpoint?name=John&age=30',
{
method: 'GET'
}
);
const data = await response.json();
setData(data);
};
fetchData();
}, []);
return (
<div>
{data ? (
<p>Received data: {JSON.stringify(data)}</p>
) : (
<p>Loading data...</p>
)}
</div>
);
}
This component will send a GET request to the https://my-api.com/endpoint endpoint with the query parameters' name and age included in the request. When the response is received, the component will update the data state variable and display the received data.