Javascript(Typescript) Generic Api Call Service

I’m building a SSR application with React and Next js and this application will communicate with with the Rest service already created. Application must send request to Rest service on both client side and server side. So I have to create one ApiCall service works both client side and server side. I tried build something but I think its not good.

ApiCall.ts

export function apiCall<T extends BaseQuery>(
 query: T,
 options?: UseQueryOptions<T>,
 ctx?: GetServerSidePropsContext
): QueryResult<T> {
    const [data, setData] = GState()(null);
    const [error, setError] = GState()(null);
    const [loading, setLoading] = GState()<Boolean>(true);

    const headersWithToken = headers(TOKEN.get(ctx.req));
    const variables: any = options.variables;

    const queryP = query(variables, headersWithToken)
    .then((respData) => {
       setData(respData);
       setLoading(false);
       return respData;
    })
    .catch((e) => {
       setLoading(false);
       setError("ERROR");
    });

    return {
       data: data,
       error: error,
       loading: loading,
       query: queryP,
   };
}

GState.ts Closure

const GState = function () {
   let _val;

   function useState<T>(initialValue: T) {
     _val = _val || initialValue;

     function setState(newVal: T) {
        _val = newVal;
     }

     function getState(): T {
       return _val;
     }
     return [getState, setState];
   }
return useState;
};

export default GState;

Api endpoints

const getCredit = (headers: {}) => Promise<ICreditResponse> = (headers) => {
  return ApiService.setHeaders(headers).getReq({
    route: "/credits/my",
    isPrivate: true,
  });
};

const healthCheckReq = (headers: {}) => Promise<string> = (headers) => {
  const apis = ApiService;
  return apis.getReq({ route: `/health`, isPrivate: false });
};

const getMerchantShippingDays = (
  s: {
    merchantId: string;
  },
  headers: {}
) => Promise<IShippingDaysResponse> = ({ merchantId }, headers) =>
    ApiService.setHeaders(headers).getReq({
      route: `/shippingDays/merchant/${merchantId}`,
      isPrivate: true,
});

Example Usage :

export default function Health({ health }: HealthProps) {

  const { data: getHealthData, loading: getHealthLoading } = apiCall(
     queryEndpoints.healthCheckReq,
     { variables: { id: "1" } }
  );

  const __ = (
     <AppContainer>
        <Container fluid>
           {!getHealthLoading() && getHealthData().map(data => 
              <Row>{data.id}</Row>
           )}
       </Container>
    </AppContainer>
 );

  return __;
}

export const getServerSideProps: GetServerSideProps = async (
  ctx: GetServerSidePropsContext
  ) => {
     const { data: healthData, loading: healthLoading, query } = apiCall(
       queryEndpoints.healthCheckReq,
       { variables: { id: "1" } },
       ctx
    );

    await query;

    return { props: { health: healthData } };
};

I need advice for that api service. How can I improve that or if I don’t need this service how can I do request to rest service with generic functions

Go to Source
Author: zblash