Fetch data with full control using fetch
Use the native fetch API when your component or utility needs complete control over a backend request. This approach works well when you need to:
- Fetch data conditionally or outside the component lifecycle
- Combine multiple backend calls or chain them with custom logic
- Manually handle headers, retries, cancellations, or error handling
This pattern gives you full flexibility. Unlike useC3Action, you must manage request timing, response state, and cleanup manually.
Set up the WindTurbine Type
This topic builds on the WindTurbine Type described in Fetch data with useC3Action. If you haven't set up that Type yet, start there first.
Fetch WindTurbine data in a React component
The following component sends a request to the backend when the component mounts. It stores the response in local state and renders the result in a table.
TypeScript
// {package}/ui/c3/src/customInstances/WindTurbine.FetchGrid.tsx
import React from 'react';
const FetchGrid = () => {
const [rows, setRows] = React.useState([]);
React.useEffect(() => {
let isSubscribed = true; // Track whether the component is still mounted
// Send a POST request to fetch turbines with status = 1 (RUNNING)
fetch('api/8/WindTurbine/getWindTurbineByStatus', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ status: 1 })
})
.then((res) => res.json())
.then((data) => {
if (isSubscribed) {
setRows(data); // Save the result in local component state
}
})
.catch((error) => {
console.error('Fetch error:', error);
});
// Cleanup function to avoid setting state if component unmounts
return () => {
isSubscribed = false;
};
}, []);
return (
<table>
<thead>
<tr>
<th>Serial Number</th>
<th>Manufacturer</th>
<th>Location</th>
<th>Installed</th>
</tr>
</thead>
<tbody>
{rows.map((row) => (
<tr key={row.id}>
<td>{row.serialNumber}</td>
<td>{row.manufacturer}</td>
<td>{row.location}</td>
<td>{new Date(row.installationDate).toLocaleDateString()}</td>
</tr>
))}
</tbody>
</table>
);
};
export default FetchGrid;When to use this pattern
Use the native fetch API instead of useC3Action or Redux when:
- You need total control over the request
- You must coordinate multiple backend actions
- You want to use
fetchin utility functions, hooks, oruseEffect