The Fetch API allows you to make network requests similar to XMLHttpRequest (XHR). It’s a promise-based global object in JavaScript that’s built into most modern browsers.
Here’s a basic example of using Fetch API in a React component to load data from a server:
```
import React, { useState, useEffect } from ‘react’;
function MyComponent() { const [data, setData] = useState([]);
useEffect(() => { fetch(‘https://api.myserver.com/data’) .then(response => response.json()) .then(data => setData(data)); }, []); // This empty array means the effect will only run once (like componentDidMount) return (export default MyComponent;
```
In this example, we’re using the Fetch API to load data from `https://api.myserver.com/data`. This call is made inside `useEffect` to ensure it’s done after the component is mounted.
The fetch function returns a promise, which resolves to the Response to that request, whether it is successful or not. You can then call the `json()` method on the response to parse the data as JSON.
This will update the component state and cause a re-render.
NOTE:
- Always check that the fetch was successful by checking if `response.ok` is true before parsing the JSON. Else, handle the error appropriately.
- Fetch API is not supported in every browsers (like IE), you might need to use a polyfill like `whatwg-fetch` or switch to `axios`.
- Error handling is not demonstrated in above example, always include error handling in your production level code.