question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Example for axios

See original GitHub issue

With axios it’s handy to “define requests” using a request object, for example like this:

import axios, { AxiosRequestConfig } from 'axios';

const request: AxiosRequestConfig = {
  baseURL: 'https://api.example.com',
  withCredentials: true,
  method: 'GET',
  url: '/search',
  params: {
    term: 'foobar',
  },
};

const response = await axios(request);
const data = response.data;

But from what I can gather, the key I can pass in to useSWR has to be a string? I can’t find any of your included examples that uses anything other than a simple string either. In the readme, there’s a short mention of using arrays, which can include both strings and objects, but it doesn’t mention what the fetcher would actually look like, and it also says the key comparison is shallow, so with my request object above here, I assume that means a change in request.params.term would not be picked up?

Would it be possible for someone to add an example of how one can use useSWR with axios and a request object like this? Or is it perhaps not possible to do that?

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:1
  • Comments:11 (8 by maintainers)

github_iconTop GitHub Comments

14reactions
o-alexandrovcommented, Dec 2, 2019

@Svish Thank you for the example. In case anyone interested, a typed version of this example:

import axios, { AxiosError, AxiosRequestConfig, AxiosResponse } from "axios"
import useSWR, { ConfigInterface } from "swr"

export const useSWRAxios = <Data extends {}>(
  request: Omit<AxiosRequestConfig, "baseURL" | "method" | "data">,
  config?: ConfigInterface,
) => {
  const requestModified: AxiosRequestConfig = {
    ...request,
    method: `GET`,
  }
  const configModified: ConfigInterface = {
    ...config,
    // global customizations
  }
  /**
   * Axios has a wrapper object around data => filter response
   */
  const { data: response, ...responseUseSWR } = useSWR<
    AxiosResponse<Data>,
    AxiosError
  >(
    JSON.stringify(requestModified),
    async () => axios(requestModified),
    configModified,
  )
  const { data, ...responseAxios } = response || {}
  return { ...responseUseSWR, responseAxios, data }
}
10reactions
shudingcommented, Nov 21, 2019

When using an array as the key, SWR will pass those items as arguments to the fetcher function:

useSWR([A, B, C, ...], fetcher)
// calls fetcher(A, B, C, ...)

For your specific case, I’d do something like:

// global config because this part won't change
const getRequest: AxiosRequestConfig = {
  baseURL: 'https://api.example.com',
  withCredentials: true,
  method: 'GET'
};

function App () {
  // inside component
  const params = useMemo(() => ({ term }), [term])
  useSWR(
    ['/search', params],
    (url, params) => axios({ ...getRequest, url, params }).then(res => res.data)
  )
}

or simpler:

// global config because this part won't change
const getRequest: AxiosRequestConfig = {
  baseURL: 'https://api.example.com',
  withCredentials: true,
  method: 'GET'
};

const fetchTerm = (url, term) =>
  axios({ ...getRequest, url, params: { term } }).then(res => res.data)

function App () {
  // inside component
  useSWR(['/search', term], fetchTerm)
}

The major reason of shallow comparison is performance. So it will always render faster, and it will reuse the stale data if the same url + params pair has occurred before.

Thanks for the feedback! We will definitely improve the readme and create an example for axios.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Minimal Example | Axios Docs
A little example of using axios ... const axios = require('axios').default; // axios. ... Make a request for a user with a given...
Read more >
Axios tutorial - GET/POST requests in JavaScript with Axios
Axios tutorial shows how to generage requests in JavaScript using Axios client library. Axios is a promise based HTTP client for the browser ......
Read more >
How to make HTTP requests with Axios - LogRocket Blog
In this tutorial, we'll demonstrate how to make HTTP requests using Axios with clear examples, including how to make an Axios POST request...
Read more >
axios/axios: Promise based HTTP client for the browser and ...
Promise based HTTP client for the browser and node.js - GitHub - axios/axios: Promise based HTTP client for the browser and node.js.
Read more >
Making HTTP requests with Axios - CircleCI
Axios is a promise-based HTTP library that lets developers make requests to either their own or a third-party server to fetch data.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found