Hooks

What is that, and how use it?

Hooks are optional functions that can be passed per-request to run custom logic at key moments in the request lifecycle.


Basic Example

const hooks: ShapeRQHooks = {
  onRequest: () => {
    console.log("Starting request...");
  },
  onResponse: (data) => {
    console.log("Response data:", data);
  },
  onError: ({error}) => {
    console.error("Error in request!", error);
  },
};

await httpGet("Main", "user/me", { hooks });

onRequest

Runs before the request is sent.

Example (React)
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);

const hooks: ShapeRQHooks = {
  onRequest: () => {
    setLoading(true);
    setError(null);
  },
};

useEffect(() => {
  const fetchData = async () => {
    await httpGet("myApi", "/endpoint", { hooks });
  };

  fetchData();
}, []);

onResponse

Called after a successful request with no server-side errors.

Example (React)
onResponse: (responseData) => {
  setData(responseData);
  setLoading(false);
}

onError

Called when the request fails, including network issues or server errors.

Example (React)
onError: ({error}) => {
  setError(error.message ?? "Something went wrong");
  setLoading(false);
}

Also you can use onError for retries

let retryCount = 0
...
    onError: async ({error, retry}) => {
        if (retryCount < 3) {
            retryCount++
            return await retry()    
        }
        console.log("Error on request!")
    }
...

Hook Summary

Hook
Trigger
Async Allowed

onRequest

Before request

onResponse

After successful response (2xx)

onError

On any failure or thrown error

Last updated