Home > front end >  How to use SWR with generic T?
How to use SWR with generic T?

Time:12-31

I have wrapped the SWR into a custom hook:

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;

And I call it:

  const { data } = useFetch<Cart>('myUrl', {
    method: MethodTypes.POST,
    body: {
       myBodyObj
    }
  });

Cart type:

export type Cart = {
  cartId: string;
  items: Array<CartItem>;
};

I can see that I get a 200 response so the call goes through but my data is always undefined. What have I missed here?

CodePudding user response:

useSWR's first arg should be key.

  • Related