Building a simple react hook api call with typescript
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.
import { useState } from "react"
import { getUser } from "../api/api"
interface User {
name: string;
email: string;
age: number;
}
export default (): [(id: string) => void, User, string] => {
const [user, setUser] = useState<User>({ name: "", email: "", age: 0 });
const [errorMsg, setErrorMsg] = useState("");
const getUserTest = async (id: string) => {
try {
const user = await getUser(`/user/${id}`);
setUser(user);
setErrorMsg("");
} catch (error) {
setErrorMsg(error);
}
};
return [getUserTest, user, errorMsg];
};
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.
import * as React from "react";
import "./styles.css";
import useTest from "./hook";
export default function App() {
const [getUser, user, errorMessage] = useTest();
return (
<div className="App">
<h1>Simple API Hook Demo</h1>
<button onClick={() => getUser("123")}>Get User</button>
<div>
<h5>{user.name}</h5>
<h6>{user.email}</h6>
<h6>{user.age}</h6>
<h6 style={{ color: "red" }}>{errorMessage}</h6>
</div>
</div>
);
}
You can find a link to a demo sandbox here
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.