39
loading...
This website collects cookies to deliver better user experience
const {
data,
isError,
isFetched,
isLoading,
...etc,
} = useQuery('todos', getTodos);
useQuery
hook takes in a "query key" (the key for the data in the cache) and a function that "queries" data via an API.useQuery
that uses the native fetch
API and another that uses a custom fetch wrapper:// some-component.js
const result = useQuery('cars', () => {
const resp = await fetch('/api/v1/cars', { method: 'GET' });
return await resp.json();
});
// another-component.js
import fetchClient from './fetch-client';
const result = useQuery('cars', async () => {
const resp = await fetchClient('/api/v1/cars');
return await resp.json();
});
fetchClient
is the intended way to make API requests as it encapsulates logic, error handling, preferred settings, etc.// api.js
const defaultOptions = { method: 'GET' };
export async function fetcher(url, options = defaultOptions) {
const resp = await fetch(url, options);
return await resp.json();
}
export * from 'react-query';
// some-component.js
import { fetcher, useQuery } from './api.js';
const result = useQuery('cars', async () => {
return await fetcher('/api/v1/cars');
});
useDispatch
):// api.js
const defaultOptions = { method: 'GET' };
async function fetcher(url, options = defaultOptions) {
const resp = await fetch(url, options);
return await resp.json();
}
export function useFetcher() {
return fetcher;
}
export * from 'react-query';
// some-component.js
import { useFetcher, useQuery } from './api.js';
const fetcher = useFetcher();
const result = useQuery('cars', async () => {
return await fetcher('/api/v1/cars');
});
fetcher
in a wrapper around useQuery
:// api.js
import { useQuery as baseUseQuery } from 'react-query';
const defaultOptions = { method: 'GET' };
async function fetcher(url, options = defaultOptions) {
const resp = await fetch(url, options);
return await resp.json();
}
function useQuery(queryKey, query) {
return useBaseQuery(queryKey, async () => {
return await fetcher(query);
});
}
// some-component.js
import { useQuery } from './api.js';
const result = useQuery('cars', '/api/v1/cars');
useQuery
can be seen most clearly in our latest wrapper.// api.js
import { kebabCase } from 'lodash';
import { useQuery as baseUseQuery } from 'react-query';
const defaultOptions = { method: 'GET' };
async function fetcher(url, options = defaultOptions) {
const resp = await fetch(url, options);
return await resp.json();
}
function useQuery(query) {
return useBaseQuery(kebabCase(query), async () => {
return await fetcher(`/api/v1/${query}`);
});
}
// some-component.js
import { useQuery } from './api.js';
const result = useQuery('cars');
useQuery
to better fit our needs.