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

What is the best way to call a method within a TypeScript class using its name as a string while already inside the class itself?

Currently, I am developing a class that automates the creation of routes for Express and invokes a function in a controller. However, upon trying to execute this[methodName](req, res), I come across an error message stating: 'Element implicitly has an ...

Automate the process of replacing imports in Jest automatically

Currently, I am in the process of setting up a testbench for a more intricate application. One challenge we are facing is that our app needs to call backend code which must be mocked to ensure the testbench runs efficiently. To address this issue, we utili ...

Implementing the handling of multiple button events in a ListView through onclick function

Currently, I have a listview with three buttons that need to trigger the same method checkInstall on multiple button clicks. However, I am unsure of how to achieve this. Below is the relevant code snippet: html file: <ListView [items]="allAppsList" c ...

Wrapping an anonymous function in a wrapper function in Typescript can prevent the inferred typing

I am encountering an issue with typing while coding: function identity<T>(v: T): T{ return v; } function execute(fn: {(n: number):string}) {} execute((n) => { // type of n is 'number' return n.toFixed(); }) execute(identity(( ...

Utilize an external JavaScript function within a React and TypeScript document

I have encountered an issue in my React/Next.js/TypeScript file where I am trying to load the YouTube iframe API in my useEffect hook. Here is the code snippet: useEffect(() => { const tag = document.createElement('script'); tag.src = ...

What is the best way to update state from a triple-layered object?

I am currently working with a nested object that I need to update using setState. Payloads export interface DentistPayload { croNumber: string; person: PersonPayload; } export interface PersonPayload { fullName: string; birthdate: string; cpfNu ...

How can I emphasize the React Material UI TextField "Cell" within a React Material UI Table?

Currently, I am working on a project using React Material UI along with TypeScript. In one part of the application, there is a Material UI Table that includes a column of Material TextFields in each row. The goal is to highlight the entire table cell when ...

Typescript error encountered in customized PipeLine class

I am currently developing a web scraping application using Puppeteer. In this project, I aim to create a PipeLine class that will take the current instance of the page and expose an add method. This add method should accept an array of functions with the t ...

Bringing in the typescript 4 package to use in typescript version 3.8.3

I've been working on a project that is utilizing typescript 3.8.3, and I'm currently attempting to import a newer package (specifically win32-api). I initially didn't anticipate any issues since the package is compiled to JavaScript. At wor ...

What is the best way to create a general getter function in Typescript that supports multiple variations?

My goal is to create a method that acts as a getter, with the option of taking a parameter. This getter should allow access to an object of type T, and return either the entire object or a specific property of that object. The issue I am facing is definin ...

Adding key/value pairs to an array of objects in RxJS Observables can be easily

I currently have an Angular app with state management that retrieves data from a database in observables. Here is an example of the interfaces I am working with: interface Service { id: number, name: string, category_id: number, } interface Category ...

What is the best way to send an object to an Angular form?

I am facing an issue with my Spring entity, Agent, which includes an Agency object. When adding a new agent, I need to pass the agency as an object in the Angular form. While the backend code is functioning correctly, I am struggling to figure out how to p ...

Struggling with using Redux with tassign in Angular (typescript) to combine state.array and action.array. However, encountering an issue where state.array.join is not a function

Redux function to combine all videos: function combineAllVideos(state, action) { return tassign(state, { allVideos: state.allVideos.concat([action.data]) }); } Declaration + State for all videos array: allVideos: Array<Object>; OR allVid ...

The use of custom loaders alongside ts-node allows for more flexibility

Is it possible to utilize ts-node with a custom loader? The documentation only mentions enabling esm compatibility. ts-node --esm my-file.ts I am attempting to implement a custom loader for testing an ESM module, but I prefer not to rely on node for compi ...

Retrieve the property of a Typescript object using a template argument

I am looking to develop a Typescript Collection class that can locate items by field. Here is an example of what I have in mind: class Collection<T, K keyof T> { private _items: T[]; public isItemInCollection(item: T) { return _item ...

The specified type '{ children: Element; ref: MutableRefObject<HTMLDivElement>; }' cannot be matched with type 'IntrinsicAttributes & RefAttributes<HTMLDivElement>' in the assignment

Encountering an issue with fowardRef in ReactJS where everything seems fine, but an error pops up: Type '{ children: Element; ref: MutableRefObject<HTMLDivElement>; }' is not assignable to type 'IntrinsicAttributes & SectionContent ...

What is the best way to insert information into my SQLite database?

Hey there! I'm new to programming and recently started working on an IONIC App. However, I've hit a roadblock. My goal is to create a phone book feature where users can get random JSON contacts and save them to their sqlite database. Here's ...

Tips for configuring Angular 2 to send all requests in the form of application/x-www-form-urlencoded

My experience with Angular 1 has helped me in understanding how to implement a similar solution, but I'm stuck on the final step. Just like before, the backend developer for our application is set up to accept requests with type application/x-www-for ...

Leveraging Next.js with TypeScript and babel-plugin-module-resolver for simplified import aliases

I am currently in the process of setting up a Next.js project with typescript. Despite following multiple guides, I have encountered an issue concerning import aliases. It's unclear whether this problem stems from my configuration or from Next.js its ...

In Angular 8, a communication service facilitates interaction between parents and children

Using a Sharing service, I am able to pass data from my app component to the router-outlet render component. While I have been successful in passing strings and other data, I am now looking for a way to retrieve data from an API and share it with a compone ...