He envuelto el SWR en un gancho personalizado:
import useSWR from 'swr'; export enum MethodTypes { POST = 'POST', PUT = 'PUT', GET = 'GET', DELETE = 'DELETE', PATCH = 'PATCH' } type QueryBody = { method: MethodTypes; body: Object; }; const useFetch = <T>(url: string, dataObj: QueryBody) => { const fetcher = async () => { return await fetch(url, { method: dataObj.method, body: JSON.stringify(dataObj.body) }).then((res) => { return res.json(); }); }; const { data, error } = useSWR<T>(fetcher); return { data, error }; }; export default useFetch;Y lo llamo:
const { data } = useFetch<Cart>('myUrl', { method: MethodTypes.POST, body: { myBodyObj } });Tipo de carrito:
export type Cart = { cartId: string; items: Array<CartItem>; };Puedo ver que obtengo una respuesta 200, por lo que la llamada se realiza, pero mis datos siempre están indefinidos. ¿Qué me he perdido aquí?
El primer argumento de useSWR debería ser clave.