React Function Component - Fetch (Ajax)
Articles Related
Plugin combo - Component related: Nothing was found.
Example
function MyComponent() {
const [isLoaded, setIsLoaded]=React.useState(false);
const [items, setItems]=React.useState(null);
const [error, setError] = React.useState(null);
React.useEffect(() => {
fetch("/doc/json/items.json")
.then(res => res.json())
.then(
(result) => { setItems(result.items); setIsLoaded(true); },
// Note: it's important to handle errors here instead of a catch() block so that we don't swallow exceptions from actual bugs in components.
(error) => { setError(error); setIsLoaded(true); }
)
});
if (error) {
return (<div>Error: {error.message}</div>);
} else if (!isLoaded) {
return (<div>Loading...</div>);
} else {
return (
<ul>
{items.map(item => (
<li key={item.name}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}
ReactDOM.render(
<MyComponent/>,
document.getElementById('root')
);
<div id="root"></div>