Best way to access http status code? #562
-
I would like to be able to access My end goal is to have a behaviour when it returns I am wondering how
|
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 8 replies
-
Yep I had a very similar question and looks like you have a solution to get both the data and status! #572 Interested in what the best practices are. |
Beta Was this translation helpful? Give feedback.
-
Another option is to throw a custom error you can attach metadata to, this is how we typically handle this pattern. interface FetchItemOptions {
method: string;
body?: unknown;
}
class FetchError extends Error {
constructor(public res: Response, message?: string) {
super(message)
}
}
const fetchItem = (path: string, options: FetchItemOptions) => {
const headers = {
'Content-Type': 'application/json',
Accept: 'application/json',
};
return fetch(`${PUBLIC_API_URL}/${path}`, {
method: options.method,
headers,
body: options.body ? JSON.stringify(options.body) : undefined,
}).then(async (response) => {
const data = await response.json();
if (response.ok) {
return data;
} else {
throw new FetchError(response)
}
});
};
function fetchItemQueryFn(_key: string, itemId: number) {
return fetchItem('/items/' + itemId, { method: 'get' })
}
const MyComponent = () => {
const { data } = useQuery(['item', 1], fetchItemQueryFn, {
onError(err: FetchError) {
if (err.res.status === 401) {
window.location.href = '/login';
}
}
})
}
|
Beta Was this translation helpful? Give feedback.
Another option is to throw a custom error you can attach metadata to, this is how we typically handle this pattern.