TanStackT
TanStack2y ago
1 reply
moderate-tomato

React Query with apisauce

I'm utilizing the https://github.com/infinitered/apisauce library for data requests. The challenge lies in the uniform flow of responses, whether they indicate success or failure. The promise in apisauce never utilizes rejection, which means that useQuery cannot capture it directly and isError always false. Hence, I'm wondering how I can employ useQuery to handle errors when response.ok=false.

Response JSON
{
    "duration": 285,
    "problem": "CLIENT_ERROR",
    "originalError": {
        ...
    },
    "ok": false,
    "status": 400,
    "headers": {
        "content-length": "0",
        "content-type": "text/html; charset=utf-8"
    },
    "config": {
        ...
    },
    "data": null
}


import { create } from 'apisauce';

import { useQuery } from '@tanstack/react-query';

const api = create({
  baseURL: 'https://httpbin.org/',
  headers: { Accept: 'application/json' },
});

api.addMonitor((res) => {
  console.log('monitor', res);
});

export default function Card() {
  const todos = useQuery({ queryKey: ['abc'], queryFn: () => api.get('status/400') });
  return (
    <div className="card">
      {todos.isSuccess && <div>Success : {todos.data.status}</div>}
      {todos.isError && <div>{todos.error.message} This line never gets executed.</div>}
    </div>
  );
}
GitHub
Axios + standardized errors + request/response transforms. - infinitered/apisauce
GitHub - infinitered/apisauce: Axios + standardized errors + reques...
Was this page helpful?