useQuery

Phillmont MuktarAI Engineer
Languages

Implement a useQuery hook that manages a promise that can be used to fetch data.

Examples

export default function Component({ param }) {
const request = useQuery(async () => {
const response = await getDataFromServer(param);
return response.data;
}, [param]);
if (request.status === 'loading') {
return <p>Loading...</p>;
}
if (request.status === 'error') {
const message =
request.error instanceof Error
? request.error.message
: String(request.error);
return <p>Error: {message}</p>;
}
return <p>Data: {request.data}</p>;
}

Arguments

  1. fn: () => Promise: A function that returns a promise
  2. deps: DependencyList: An array of dependencies, similar to the second argument of useEffect. Unlike useEffect, this defaults to []

Returns

The hook returns an object that has different properties depending on the state of the promise.

  • Pending:
    • status: 'loading': The promise is still pending
  • Rejected:
    • status: 'error': The promise was rejected
    • error: unknown: The value that caused the promise to be rejected
  • Fulfilled:
    • status: 'success': The promise was resolved
    • data: The data returned when the promise from fn resolves

Notes

  • The hook should return { status: 'loading' } when it starts a new request.
  • Changing deps should start a new request and ignore stale results from earlier requests.
  • Unmounting should prevent pending promise callbacks from updating state.
  • The hook does not need caching, retries, request deduplication, or cancellation of the underlying async operation.

Hints

New

Asked at these companies

Unlock company signalsPremium shows which companies ask this question so you can prioritize practice by target company.
Unlock

Loading editor

    useQuery | JavaScript Interview Questions with Solutions