Custom hook (data requests)
Introduction
The first example (option i) is a basic set up on how to fetch data. The second example (in codesandbox) allows parameters to be passed and thereby can be reused more easily with different endpoints. The third example (option ii) lets you pass parameters and utilise the returned object.
Code
Option I
// useHook.tsx
export const useDataHook = () => {
const [isLoading, setIsLoading] = React.useState(true);
const [data, setData] = React.useState<Character[]>([]);
React.useEffect(() => {
fetch("https://hp-api.onrender.com/api/characters")
.then((response) => response.json())
.then((data) => {
setIsLoading(false);
setData(data);
});
}, [setData]);
return { isLoading, data };
};
// Main.tsx
const { isLoading, data } = useDataHook();Option II
export const useBuildObject = () => {
return React.useCallback((isARealBoy: boolean, title: string) => {
const params = {
id: 3434,
isARealBoy,
title
};
return params;
}, []);
};
const buildObj = useBuildObject();
const params = buildObj(true, "Pinocchio");
console.log(params);