Building a simple react hook api call with typescript

Jesse Langford
2 min readJan 1, 2021

I recently started building my own hooks in react and I wanted to share one that found particularly useful.

Making api calls is something I do frequently, so one of the first hooks I set out to make was a simple hook that makes an api call, returns data, or an error message if something goes wrong.

Here is the full hook file, I’ll spend the rest of the article going through it pice by piece.

The first line of the hook is one of the most important

export default (): [(id: string) => void, User, string] =>

the [(id: string) => void, User, string] specifies all the return types that the hook provides. Typescript wont complain if you don’t provide this, but without it your return types will be misinterpreted and you wont be able to call the hook.So be sure to always specify your return types for functions.

The second part specifies the data we want to to return.

const [user, setUser] = useState<User>({ name: “”, email: “”, age: 0 });
const [errorMsg, setErrorMsg] = useState(“”);

Thirdly, we have a simple asynchronous function to go and fetch our user.

const getUserTest = async (id: string) => {
try {
const user = await getUser(`/user/${id}`);
setUser(user);
setErrorMsg(“”);
} catch (error) {
setErrorMsg(error.message);
}
};

Lastly, we have our array of items we want to return. Note how each value from left to right matches the return types in the first section.

return [getUserTest, user, errorMsg];

And that’s all there is to it. Now you can import the hook and call it.

You can find a link to a demo sandbox here: https://codesandbox.io/s/vigilant-resonance-ysmtr?file=/src/App.tsx

This is a pretty simple example, in my next article I will show to make this hook generic so you could use it for multiple api calls.

--

--