A react machine state hook to handle your network requests.
Data that returns the network call.
Data could be defined with a generic when we define our hook to be used:
const { data, meta, signal, actions } = useNetworkState<string>();
The hook will return a loading state.
The hook will return an error state.
The hook will return an error message.
Turns the loading state to true.
Turns the loading state to false.
Turns the loading state to false and abort the network call.
Turns the error state to false and initialize error message to ''.
Turns the loading state to false, the error state to true and sets the error message.
Set data that should return the hook.
Set the loading state.
Reset the abort controller to a new one.
This action is important when you want to abort the network call.
actions.start();
try {
const response = await fetch(url, { signal }) as any;
const d = await response.json();
actions.setData(d);
} catch (error: any) {
if (error as DOMException) {
actions.resetSignal();
return;
}
actions.setError();
} finally {
actions.end();
}
Set the abort controller.
import { useNetworkState, UseNetworkStateReturn } from 'useNetworkSate';
type UseFetchFromMyApiReturn = {
data: unknown;
meta: {
isLoading: boolean;
isError: boolean;
errorMessage: string;
};
fetchFromMyApiExampleByName: (name: string) => UseNetworkStateReturn;
};
export default function useFetchFromMyApi(): UseFetchFromMyApiReturn {
const { data, meta, actions, signal } = useNetworkState();
const fetchFromMyApiExample = async (name = 'defaultName') => {
actions.startRequest();
try {
const response = await fetch(`https://my-api.com/?name=${name}`, signal);
} catch (error) {
actions.setErrorState(error);
} finally {
actions.endRequest();
}
};
return { data, meta, fetchFromMyApiExampleByName };
}
import { useEffect } from 'react';
import useFetchFromMyApi from './useFetchFromMyApi';
export default function App() {
const { data, meta, fetchFromMyApiExampleByName } = useFetchFromMyApi();
useEffect(() => {
fetchFromMyApiExampleByName('Rick');
}, []);
if (meta.isLoading) {
return <div>Loading...</div>;
}
return <div>data: {JSON.stringify(data, null)}</div>;
}