Leverage the power of InfiniteSWR in your project by integrating it seamlessly with

If you're looking for a comprehensive example of how to integrate useSWR hooks with axios and typescript, check out the official repository here.

import useSWR, { SWRConfiguration, SWRResponse } from 'swr'
import axios, { AxiosRequestConfig, AxiosResponse, AxiosError } from 'axios'

export type GetRequest = AxiosRequestConfig | null

interface Return<Data, Error>
  extends Pick<
    SWRResponse<AxiosResponse<Data>, AxiosError<Error>>,
    'isValidating' | 'revalidate' | 'error' | 'mutate'
  > {
  data: Data | undefined
  response: AxiosResponse<Data> | undefined
}

export interface Config<Data = unknown, Error = unknown>
  extends Omit<
    SWRConfiguration<AxiosResponse<Data>, AxiosError<Error>>,
    'initialData'
  > {
  initialData?: Data
}

export default function useRequest<Data = unknown, Error = unknown>(
  request: GetRequest,
  { initialData, ...config }: Config<Data, Error> = {}
): Return<Data, Error> {
  const { data: response, error, isValidating, revalidate, mutate } = useSWR<
    AxiosResponse<Data>,
    AxiosError<Error>
  >(
    request && JSON.stringify(request),
    /**
     * NOTE: Typescript thinks `request` can be `null` here, but the fetcher
     * function is actually only called by `useSWR` when it isn't.
     */
    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    () => axios(request!),
    {
      ...config,
      initialData: initialData && {
        status: 200,
        statusText: 'InitialData',
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        config: request!,
        headers: {},
        data: initialData
      }
    }
  )

  return {
    data: response && response.data,
    response,
    error,
    isValidating,
    revalidate,
    mutate
  }
}

Would you like guidance on implementing useSWRInfinite with axios and typescript?

Answer №1

Although it may be considered outdated by some, after applying the most recent update, you can expect to see something along these lines now:

import { AxiosRequestConfig, AxiosResponse, AxiosError } from "axios";

import axios from "./request";

import useSWRInfinite, {
  SWRInfiniteConfiguration,
  SWRInfiniteResponse,
} from "swr/infinite";

export type GetRequest = AxiosRequestConfig | null;

interface InfiniteReturn<Data, Error>
  extends Pick<
    SWRInfiniteResponse<AxiosResponse<Data>, AxiosError<Error>>,
    "isValidating" | "error" | "mutate" | "size" | "setSize"
  > {
  data: Data[] | undefined;
  response: AxiosResponse<Data>[] | undefined;
}

export interface InfiniteConfig<Data = unknown, Error = unknown>
  extends Omit<
    SWRInfiniteConfiguration<AxiosResponse<Data>, AxiosError<Error>>,
    "fallbackData"
  > {
  fallbackData?: Data[];
}

export default function useRequestInfinite<Data = unknown, Error = unknown>(
  getRequest: (index: number, previousPageData: AxiosResponse<Data> | null) => GetRequest,
  { fallbackData, ...config }: InfiniteConfig<Data, Error> = {},
): InfiniteReturn<Data, Error> {
  const { data: response, error, isValidating, mutate, size, setSize } = useSWRInfinite<
    AxiosResponse<Data>,
    AxiosError<Error>
  >(
    (index, previousPageData) => {
      const key = getRequest(index, previousPageData);
      return key ? JSON.stringify(key) : null;
    },
    request => client(JSON.parse(request)),
    {
      ...config,
      fallbackData:
        fallbackData &&
        fallbackData.map(i => ({
          status: 200,
          statusText: "InitialData",
          config: {},
          headers: {},
          data: i,
        })),
    },
  );

  return {
    data: response && response.map(r => r.data),
    response,
    mutate,
    error,
    isValidating,
    size,
    setSize,
  };
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guidelines for crafting an intricate selector by utilizing mergeStyleSets and referencing a specific class

I'm currently in the process of developing a web application using ReactJS. In my project, I have the following code: const MyComponent = (props: { array: Array<Data> }) => { const styles = mergeStyleSets({ container: { ...

Here's a revised version: "How to link a lambda layer with a function in a serverless.ts file using the

When working with the serverless framework using the typescript template, a serverless.ts file is generated. I am currently integrating lambda layers with existing functions and encountering a typescript error. The error message reads: "Type '{ Ref: ...

The expected property 'label' is not found in the object type '{ handleClick: () => void; }', but it is required in the object type '{ handleClick: () => void; label: string; }'

I'm encountering difficulties when describing the types of my props. The issue arises with the following code: <PostButton handleClick={props.upvote}/> <PostButton2 handleClick={props.downvote}/> An error message is displayed: Pro ...

Can you explain the purpose of this TypeScript code snippet? It declares a variable testOptions that can only be assigned one of the values "Undecided," "Yes," or "No," with a default value of "Undecided."

const testOptions: "Undecided" | "Yes" | "No" = "Undecided"; Can you explain the significance of this code snippet in typescript? How would you classify the variable testOptions? Is testOptions considered an array, string, or another d ...

How can I implement dynamic styling for the rows in the PrimeNG table?

I have the MyObject.ts file with the following properties: name: String rowStyle: String In addition, I have a MyComponent.ts file containing: myObject1: MyObject = new MyObject(); myObject2: MyObject = new MyObject(); myObjectList: MyObject[] = []; myO ...

Steps for Properly Defining Next.js getServerSideProps as a Function Declaration

I've been working on implementing getServerSideProps (additional information available here, and detailed API documentation here), but my challenge lies in utilizing it as a function declaration instead of an expression. Despite searching for relevant ...

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

Exploring disparities between the Client SDK and Admin SDK in conducting firestore queries

I am encountering difficulties with my query while running it in Firebase Functions. It functions perfectly on the client side, but fails to work in Functions. I am curious if there is a way to modify it to function with Admin SDK as well. Am I making any ...

Verify user authentication status on the server using Vercel and NextAuth

After successfully running my blog on localhost, I encountered an issue when deploying it on Vercel. The page to create a post kept returning error 504 with no additional information in the logs. I made sure to update the NEXTAUTH_URL with the URL provide ...

Utilize various interfaces for a single object

I'm working on a Typescript project where I need to pass the same object between multiple functions with different interfaces. These are the interfaces: export interface TestModel { fileName:string, year:number, country:string } export interfac ...

Is there any way to deactivate the saved query in react-admin without having to develop a new component?

The latest version of react-admin, version 4, introduced a new feature that allows saving filters. I'm curious about how to disable this functionality without having to create an additional filter button. https://i.stack.imgur.com/uTrUe.gif ...

The implementation of useState is not functioning properly when used within a parent useState function

I am currently working with a Ticket child class where I set the total amount after changing the number of tickets. The issue I am encountering is that the setNumber function doesn't seem to work properly unless the setTotal function is commented out. ...

Developing a custom package containing personally crafted type definitions and importing them into the project

I'm in need of creating a private npm package specifically for custom type definitions (typedefs) that are hand-written d.ts files not generated by TypeScript. Since these are proprietary, they cannot be added to DefinitelyTyped. The folder structure ...

Struggling to transmit data to material dialog in Angular2+

I am facing an issue with my Material Dialog not working properly. Can anyone point out what I might be missing? product-thumbnail.ts I will use this to trigger the dialog export class ProductThumbnailComponent implements OnInit { @Input() product: Pr ...

Encountering npm3 installation errors with typyings in Angular 2?

Each time I try to sudo npm install Angular 2 modules, everything updates and installs correctly. However, I encounter the following error when the typings install is attempted: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0 ...

I'm experiencing some difficulties utilizing the return value from a function in Typescript

I am looking for a way to iterate through an array to check if a node has child nodes and whether it is compatible with the user's role. My initial idea was to use "for (let entry of someArray)" to access each node value in the array. However, the "s ...

Angular Universal causing issues with updating the DOM component

@Component({ selector: 'mh-feature-popup', template: ` <div class="full"> <div> <div class="container-fluid" [@featurepop]="state"> <div class="row"> <div class="col-xs-12 col-md-4 col-md-offse ...

Angular with D3 - Semi-Circle Graph Color Order

Can someone assist me with setting chart colors? I am currently using d3.js in angular to create a half pie chart. I would like to divide it into 3 portions, each represented by a different color. The goal is to assign 3 specific colors to certain ranges. ...

Exclude extraneous keys from union type definition

Working on a call interface that outlines its arguments using specific properties and combined variants. type P1 = {prop1: number} type P2 = {prop2: number} type U1 = {u1: string} type U2 = {u2: number} export type Args = P1 & P2 & (U1 | U2) In th ...

Struggling to locate the ID linked to a specific ObjectId and encountering issues with the import function?

Can someone help me with this issue? Error Message: ERROR TypeError: answerID.equals is not a function I am unsure why I am getting this error. Here is the code snippet: import { ObjectId } from 'bson'; export class Person{ personID: Objec ...