Sometimes, we want to make API call with hooks in React.
In this article, we’ll look at how to make API call with hooks in React.
How to make API call with hooks in React?
To make API call with hooks in React, we can do it in the useEffect
callback.
For instance, we write
const Todo = () => {
const [todo, setTodo] = React.useState(null);
const [id, setId] = React.useState(1);
const getTodo = async (id) => {
const results = await fetch(
`https://jsonplaceholder.typicode.com/todos/${id}`
);
const data = await results.json();
setTodo(data);
};
React.useEffect(() => {
if (id === null || id === "") {
return;
}
getTodo(id);
}, [id]);
return (
<div>
<input value={id} onChange={(e) => setId(e.target.value)} />
<br />
<pre>{JSON.stringify(todo, null, 2)}</pre>
</div>
);
};
to define the getTodo
which makes a get request to an endpoint to get some data.
We get the response data from the json
method.
Then we call useEffect
with a callback that calls getTodo
with id
.
The 2nd argument is [id]
so the useEffect
callback will be called when id
changes.
Conclusion
To make API call with hooks in React, we can do it in the useEffect
callback.