kandi background
Explore Kits

axios | Promise based HTTP client for the browser and node.js | Reactive Programming library

 by   axios JavaScript Version: v0.26.1 License: MIT

 by   axios JavaScript Version: v0.26.1 License: MIT

Download this library from

kandi X-RAY | axios Summary

axios is a JavaScript library typically used in Programming Style, Reactive Programming, Nodejs applications. axios has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can install using 'npm i axioswill' or download it from GitHub, npm.
Promise based HTTP client for the browser and node.js.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • axios has a medium active ecosystem.
  • It has 92140 star(s) with 9366 fork(s). There are 1219 watchers for this library.
  • There were 5 major release(s) in the last 12 months.
  • There are 240 open issues and 3300 have been closed. On average issues are closed in 186 days. There are 88 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of axios is v0.26.1
axios Support
Best in #Reactive Programming
Average in #Reactive Programming
axios Support
Best in #Reactive Programming
Average in #Reactive Programming

quality kandi Quality

  • axios has 0 bugs and 0 code smells.
axios Quality
Best in #Reactive Programming
Average in #Reactive Programming
axios Quality
Best in #Reactive Programming
Average in #Reactive Programming

securitySecurity

  • axios has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • axios code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
axios Security
Best in #Reactive Programming
Average in #Reactive Programming
axios Security
Best in #Reactive Programming
Average in #Reactive Programming

license License

  • axios is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
axios License
Best in #Reactive Programming
Average in #Reactive Programming
axios License
Best in #Reactive Programming
Average in #Reactive Programming

buildReuse

  • axios releases are available to install and integrate.
  • Deployable package is available in npm.
  • Installation instructions, examples and code snippets are available.
  • axios saves you 167 person hours of effort in developing the same functionality from scratch.
  • It has 422 lines of code, 0 functions and 95 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
axios Reuse
Best in #Reactive Programming
Average in #Reactive Programming
axios Reuse
Best in #Reactive Programming
Average in #Reactive Programming
Top functions reviewed by kandi - BETA

kandi has reviewed axios and discovered the below as its top functions. This is intended to give you an instant insight into axios implemented functionality, and help decide if they suit your requirements.

  • Converts an object to a FormData
  • Cancel a token .
  • Convert form data to JSON
  • Set proxy configuration
  • Default conversion handler .
  • Terminate the load request body
  • Builds path to target object .
  • Iterate over an object
  • Copy properties from sourceObject to destination object
  • Resolves a URL node

axios Key Features

Make XMLHttpRequests from the browser

Make http requests from node.js

Supports the Promise API

Intercept request and response

Transform request and response data

Cancel requests

Automatic transforms for JSON data

Client side support for protecting against XSRF

Installing

copy iconCopydownload iconDownload
$ npm install axios

note: CommonJS usage

copy iconCopydownload iconDownload
const axios = require('axios').default;

// axios.<method> will now provide autocomplete and parameter typings

axios API

copy iconCopydownload iconDownload
// Send a POST request
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

Creating an instance

copy iconCopydownload iconDownload
const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

Request Config

copy iconCopydownload iconDownload
{
  // `url` is the server URL that will be used for the request
  url: '/user',

  // `method` is the request method to be used when making the request
  method: 'get', // default

  // `baseURL` will be prepended to `url` unless `url` is absolute.
  // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
  // to methods of that instance.
  baseURL: 'https://some-domain.com/api/',

  // `transformRequest` allows changes to the request data before it is sent to the server
  // This is only applicable for request methods 'PUT', 'POST', 'PATCH' and 'DELETE'
  // The last function in the array must return a string or an instance of Buffer, ArrayBuffer,
  // FormData or Stream
  // You may modify the headers object.
  transformRequest: [function (data, headers) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `transformResponse` allows changes to the response data to be made before
  // it is passed to then/catch
  transformResponse: [function (data) {
    // Do whatever you want to transform the data

    return data;
  }],

  // `headers` are custom headers to be sent
  headers: {'X-Requested-With': 'XMLHttpRequest'},

  // `params` are the URL parameters to be sent with the request
  // Must be a plain object or a URLSearchParams object
  params: {
    ID: 12345
  },

  // `paramsSerializer` is an optional function in charge of serializing `params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function (params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },

  // `data` is the data to be sent as the request body
  // Only applicable for request methods 'PUT', 'POST', 'DELETE , and 'PATCH'
  // When no `transformRequest` is set, must be of one of the following types:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - Browser only: FormData, File, Blob
  // - Node only: Stream, Buffer
  data: {
    firstName: 'Fred'
  },
  
  // syntax alternative to send data into the body
  // method post
  // only the value is sent, not the key
  data: 'Country=Brasil&City=Belo Horizonte',

  // `timeout` specifies the number of milliseconds before the request times out.
  // If the request takes longer than `timeout`, the request will be aborted.
  timeout: 1000, // default is `0` (no timeout)

  // `withCredentials` indicates whether or not cross-site Access-Control requests
  // should be made using credentials
  withCredentials: false, // default

  // `adapter` allows custom handling of requests which makes testing easier.
  // Return a promise and supply a valid response (see lib/adapters/README.md).
  adapter: function (config) {
    /* ... */
  },

  // `auth` indicates that HTTP Basic auth should be used, and supplies credentials.
  // This will set an `Authorization` header, overwriting any existing
  // `Authorization` custom headers you have set using `headers`.
  // Please note that only HTTP Basic auth is configurable through this parameter.
  // For Bearer tokens and such, use `Authorization` custom headers instead.
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },

  // `responseType` indicates the type of data that the server will respond with
  // options are: 'arraybuffer', 'document', 'json', 'text', 'stream'
  //   browser only: 'blob'
  responseType: 'json', // default

  // `responseEncoding` indicates encoding to use for decoding responses (Node.js only)
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // default

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token
  xsrfCookieName: 'XSRF-TOKEN', // default

  // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
  xsrfHeaderName: 'X-XSRF-TOKEN', // default

  // `onUploadProgress` allows handling of progress events for uploads
  // browser only
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `onDownloadProgress` allows handling of progress events for downloads
  // browser only
  onDownloadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

  // `maxContentLength` defines the max size of the http response content in bytes allowed in node.js
  maxContentLength: 2000,

  // `maxBodyLength` (Node only option) defines the max size of the http request content in bytes allowed
  maxBodyLength: 2000,

  // `validateStatus` defines whether to resolve or reject the promise for a given
  // HTTP response status code. If `validateStatus` returns `true` (or is set to `null`
  // or `undefined`), the promise will be resolved; otherwise, the promise will be
  // rejected.
  validateStatus: function (status) {
    return status >= 200 && status < 300; // default
  },

  // `maxRedirects` defines the maximum number of redirects to follow in node.js.
  // If set to 0, no redirects will be followed.
  maxRedirects: 5, // default

  // `socketPath` defines a UNIX Socket to be used in node.js.
  // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
  // Only either `socketPath` or `proxy` can be specified.
  // If both are specified, `socketPath` is used.
  socketPath: null, // default

  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // `proxy` defines the hostname, port, and protocol of the proxy server.
  // You can also define your proxy using the conventional `http_proxy` and
  // `https_proxy` environment variables. If you are using environment variables
  // for your proxy configuration, you can also define a `no_proxy` environment
  // variable as a comma-separated list of domains that should not be proxied.
  // Use `false` to disable proxies, ignoring environment variables.
  // `auth` indicates that HTTP Basic auth should be used to connect to the proxy, and
  // supplies credentials.
  // This will set an `Proxy-Authorization` header, overwriting any existing
  // `Proxy-Authorization` custom headers you have set using `headers`.
  // If the proxy server uses HTTPS, then you must set the protocol to `https`. 
  proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` specifies a cancel token that can be used to cancel the request
  // (see Cancellation section below for details)
  cancelToken: new CancelToken(function (cancel) {
  }),

  // an alternative way to cancel Axios requests using AbortController
  signal: new AbortController().signal,

  // `decompress` indicates whether or not the response body should be decompressed 
  // automatically. If set to `true` will also remove the 'content-encoding' header 
  // from the responses objects of all decompressed responses
  // - Node only (XHR cannot turn off decompression)
  decompress: true // default

  // `insecureHTTPParser` boolean.
  // Indicates where to use an insecure HTTP parser that accepts invalid HTTP headers.
  // This may allow interoperability with non-conformant HTTP implementations.
  // Using the insecure parser should be avoided.
  // see options https://nodejs.org/dist/latest-v12.x/docs/api/http.html#http_http_request_url_options_callback
  // see also https://nodejs.org/en/blog/vulnerability/february-2020-security-releases/#strict-http-header-parsing-none
  insecureHTTPParser: undefined // default

  // transitional options for backward compatibility that may be removed in the newer versions
  transitional: {
    // silent JSON parsing mode
    // `true`  - ignore JSON parsing errors and set response.data to null if parsing failed (old behaviour)
    // `false` - throw SyntaxError if JSON parsing failed (Note: responseType must be set to 'json')
    silentJSONParsing: true, // default value for the current Axios version

    // try to parse the response string as JSON even if `responseType` is not 'json'
    forcedJSONParsing: true,
    
    // throw ETIMEDOUT error instead of generic ECONNABORTED on request timeouts
    clarifyTimeoutError: false,
  }
}

Response Schema

copy iconCopydownload iconDownload
{
  // `data` is the response that was provided by the server
  data: {},

  // `status` is the HTTP status code from the server response
  status: 200,

  // `statusText` is the HTTP status message from the server response
  statusText: 'OK',

  // `headers` the HTTP headers that the server responded with
  // All header names are lower cased and can be accessed using the bracket notation.
  // Example: `response.headers['content-type']`
  headers: {},

  // `config` is the config that was provided to `axios` for the request
  config: {},

  // `request` is the request that generated this response
  // It is the last ClientRequest instance in node.js (in redirects)
  // and an XMLHttpRequest instance in the browser
  request: {}
}

Global axios defaults

copy iconCopydownload iconDownload
axios.defaults.baseURL = 'https://api.example.com';

// Important: If axios is used with multiple domains, the AUTH_TOKEN will be sent to all of them.
// See below for an example using Custom instance defaults instead.
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

Custom instance defaults

copy iconCopydownload iconDownload
// Set config defaults when creating the instance
const instance = axios.create({
  baseURL: 'https://api.example.com'
});

// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

Config order of precedence

copy iconCopydownload iconDownload
// Create an instance using the config defaults provided by the library
// At this point the timeout config value is `0` as is the default for the library
const instance = axios.create();

// Override timeout default for the library
// Now all requests using this instance will wait 2.5 seconds before timing out
instance.defaults.timeout = 2500;

// Override timeout for this request as it's known to take a long time
instance.get('/longRequest', {
  timeout: 5000
});

Interceptors

copy iconCopydownload iconDownload
// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // Do something before request is sent
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

// Add a response interceptor
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

Handling Errors

copy iconCopydownload iconDownload
axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

Cancellation

copy iconCopydownload iconDownload
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// cancel the request (the message parameter is optional)
source.cancel('Operation canceled by the user.');

Browser

copy iconCopydownload iconDownload
const params = new URLSearchParams();
params.append('param1', 'value1');
params.append('param2', 'value2');
axios.post('/foo', params);

Node.js

copy iconCopydownload iconDownload
const querystring = require('querystring');
axios.post('http://something.com/', querystring.stringify({ foo: 'bar' }));

TypeScript

copy iconCopydownload iconDownload
let user: User = null;
try {
  const { data } = await axios.get('/user?ID=12345');
  user = data.userDetails;
} catch (error) {
  if (axios.isAxiosError(error)) {
    handleAxiosError(error);
  } else {
    handleUnexpectedError(error);
  }
}

Why items appends to the redux rather than replace?

copy iconCopydownload iconDownload
case ReducerTypes.GET_ALL_POSTS:
            return {
                ...state,
                posts: {
                    items: action.payload.items,
                    pagination: action.payload.pagination
                }
            };

Invalid options object. Dev Server has been initialized using an options object that does not match the API schema

copy iconCopydownload iconDownload
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:6000',
      changeOrigin: true,
    })
  );
};
-----------------------
"react-scripts": "5.*", 
"react-scripts": "4.0.3",
-----------------------
"react-scripts": "5.*", 
"react-scripts": "4.0.3",
-----------------------
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://localhost:5000',
      changeOrigin: true,
    })
  );
};

React router v6 how to use `navigate` redirection in axios interceptor

copy iconCopydownload iconDownload
import { useCallback, useEffect, useState } from "react"

export default function useAsync(callback, dependencies = []) {
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState()
  const [value, setValue] = useState()

  // Simply manage 3 different states and update them as per the results of a Promise's resolution
  // Here, we define a callback
  const callbackMemoized = useCallback(() => {
    setLoading(true)
    setError(undefined)
    setValue(undefined)
    callback()
      // ON SUCCESS -> Set the data from promise as "value"  
      .then(setValue)
      // ON FAILURE -> Set the err from promise as "error"  
      .catch((error)=> {
          setError(error)
          useNavigate()('/login')
       })
      // Irresp of fail or success, loading must stop after promise has ran
      .finally(() => setLoading(false))
      // This function runs everytime some dependency changes
  }, dependencies)

  // To run the callback function each time it itself changes i.e. when its dependencies change
  useEffect(() => {
    callbackMemoized()
  }, [callbackMemoized])

  return { loading, error, value }
}
-----------------------
import { Router } from "react-router-dom";

const CustomRouter = ({ history, ...props }) => {
  const [state, setState] = useState({
    action: history.action,
    location: history.location
  });

  useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      {...props}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
};
import { createBrowserHistory } from "history";

const history = createBrowserHistory();

export default history;
import customHistory from '../path/to/history';

...

<CustomRouter history={customHistory}>
  ... app code ...
</CustomRouter>
import axios from "axios";
import history from '../path/to/history';

export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/",
  headers: {
    "content-type": "application/json",
  },
});

api.interceptors.response.use(
  function (response) {
    return response;
  },
  function (er) {
    if (axios.isAxiosError(er)) {
      if (er.response) {
        if (er.response.status == 401) {
          history.replace("/login"); // <-- navigate
        }
      }
    }

    return Promise.reject(er);
  }
);
-----------------------
import { Router } from "react-router-dom";

const CustomRouter = ({ history, ...props }) => {
  const [state, setState] = useState({
    action: history.action,
    location: history.location
  });

  useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      {...props}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
};
import { createBrowserHistory } from "history";

const history = createBrowserHistory();

export default history;
import customHistory from '../path/to/history';

...

<CustomRouter history={customHistory}>
  ... app code ...
</CustomRouter>
import axios from "axios";
import history from '../path/to/history';

export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/",
  headers: {
    "content-type": "application/json",
  },
});

api.interceptors.response.use(
  function (response) {
    return response;
  },
  function (er) {
    if (axios.isAxiosError(er)) {
      if (er.response) {
        if (er.response.status == 401) {
          history.replace("/login"); // <-- navigate
        }
      }
    }

    return Promise.reject(er);
  }
);
-----------------------
import { Router } from "react-router-dom";

const CustomRouter = ({ history, ...props }) => {
  const [state, setState] = useState({
    action: history.action,
    location: history.location
  });

  useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      {...props}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
};
import { createBrowserHistory } from "history";

const history = createBrowserHistory();

export default history;
import customHistory from '../path/to/history';

...

<CustomRouter history={customHistory}>
  ... app code ...
</CustomRouter>
import axios from "axios";
import history from '../path/to/history';

export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/",
  headers: {
    "content-type": "application/json",
  },
});

api.interceptors.response.use(
  function (response) {
    return response;
  },
  function (er) {
    if (axios.isAxiosError(er)) {
      if (er.response) {
        if (er.response.status == 401) {
          history.replace("/login"); // <-- navigate
        }
      }
    }

    return Promise.reject(er);
  }
);
-----------------------
import { Router } from "react-router-dom";

const CustomRouter = ({ history, ...props }) => {
  const [state, setState] = useState({
    action: history.action,
    location: history.location
  });

  useLayoutEffect(() => history.listen(setState), [history]);

  return (
    <Router
      {...props}
      location={state.location}
      navigationType={state.action}
      navigator={history}
    />
  );
};
import { createBrowserHistory } from "history";

const history = createBrowserHistory();

export default history;
import customHistory from '../path/to/history';

...

<CustomRouter history={customHistory}>
  ... app code ...
</CustomRouter>
import axios from "axios";
import history from '../path/to/history';

export const api = axios.create({
  baseURL: "http://127.0.0.1:8000/",
  headers: {
    "content-type": "application/json",
  },
});

api.interceptors.response.use(
  function (response) {
    return response;
  },
  function (er) {
    if (axios.isAxiosError(er)) {
      if (er.response) {
        if (er.response.status == 401) {
          history.replace("/login"); // <-- navigate
        }
      }
    }

    return Promise.reject(er);
  }
);
-----------------------
//place all imports here

const SetupInterceptors = (navigate) => {
    axios.interceptors.response.use(
       function (response) {
           // Do something with response data
           return response;
       },
       function (error) {
           // Do something with response error
           if (error.response) {
                if (error.response.status === 401 || error.response.status === 403) {
                    navigate('/login');
    
                }
           }
           return Promise.reject(error);
      }
   );
};

export default SetupInterceptors;
import axios from "axios";


//axios configuration here

export default axios;
import SetupInterceptors from "SetupInterceptor";
import { useState } from "react";

function NavigateFunctionComponent(props) {
    let navigate = useNavigate();
    const [ran,setRan] = useState(false);

    {/* only run setup once */}
    if(!ran){
       SetupInterceptors(navigate);
       setRan(true);
    }
    return <></>;
}


function App(props) {
   return (
       <BrowserRouter>
           {<NavigateFunctionComponent />}
           <Routes>
              {/* other routes here */}
              <Route path="/login" element={<Login/>}></Route>
              {/* other routes here */}
           </Routes>
       </BrowserRouter>
   );
}
-----------------------
//place all imports here

const SetupInterceptors = (navigate) => {
    axios.interceptors.response.use(
       function (response) {
           // Do something with response data
           return response;
       },
       function (error) {
           // Do something with response error
           if (error.response) {
                if (error.response.status === 401 || error.response.status === 403) {
                    navigate('/login');
    
                }
           }
           return Promise.reject(error);
      }
   );
};

export default SetupInterceptors;
import axios from "axios";


//axios configuration here

export default axios;
import SetupInterceptors from "SetupInterceptor";
import { useState } from "react";

function NavigateFunctionComponent(props) {
    let navigate = useNavigate();
    const [ran,setRan] = useState(false);

    {/* only run setup once */}
    if(!ran){
       SetupInterceptors(navigate);
       setRan(true);
    }
    return <></>;
}


function App(props) {
   return (
       <BrowserRouter>
           {<NavigateFunctionComponent />}
           <Routes>
              {/* other routes here */}
              <Route path="/login" element={<Login/>}></Route>
              {/* other routes here */}
           </Routes>
       </BrowserRouter>
   );
}
-----------------------
//place all imports here

const SetupInterceptors = (navigate) => {
    axios.interceptors.response.use(
       function (response) {
           // Do something with response data
           return response;
       },
       function (error) {
           // Do something with response error
           if (error.response) {
                if (error.response.status === 401 || error.response.status === 403) {
                    navigate('/login');
    
                }
           }
           return Promise.reject(error);
      }
   );
};

export default SetupInterceptors;
import axios from "axios";


//axios configuration here

export default axios;
import SetupInterceptors from "SetupInterceptor";
import { useState } from "react";

function NavigateFunctionComponent(props) {
    let navigate = useNavigate();
    const [ran,setRan] = useState(false);

    {/* only run setup once */}
    if(!ran){
       SetupInterceptors(navigate);
       setRan(true);
    }
    return <></>;
}


function App(props) {
   return (
       <BrowserRouter>
           {<NavigateFunctionComponent />}
           <Routes>
              {/* other routes here */}
              <Route path="/login" element={<Login/>}></Route>
              {/* other routes here */}
           </Routes>
       </BrowserRouter>
   );
}
-----------------------
// lib/history.js
import { createBrowserHistory } from "history";
export default createBrowserHistory();

// App.jsx
import { unstable_HistoryRouter as HistoryRouter } from 'react-router-dom';
import history from "lib/history";

function App() {
  return (
    <HistoryRouter history={history}>
      // The rest of your app
    </HistoryRouter>
  );
}

// lib/axios.js
import history from "lib/history";
import storage from "utils/storage";

export const axios = Axios.create({})

axios.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    if (error.response?.status === 401) {
      storage.clearToken();
      history.push("/auth/login");
      return Promise.resolve();
    }

    return Promise.reject(error);
  }
);
-----------------------
import {createBrowserHistory} from 'history';
import {unstable_HistoryRouter as HistoryRouter} from 'react-router-dom';

let history = createBrowserHistory();

function App() {
  return (
    <HistoryRouter history={history}>
      // The rest of your app
    </HistoryRouter>
  );
}

// Usage
history.replace('/foo');
-----------------------
import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { axiosInstance } from '../custom-axios';

export const ResponseInterceptor = () => {
  const { onLogout } = useAuth();
  const { addError } = useAPIError();
  const navigate = useNavigate()


  const interceptorId = useRef<number | null>(null);

  useEffect(() => {
    interceptorId.current = axiosInstance.interceptors.response.use(undefined, (error) => {
      switch (error.response.status) {
        case 401:
          navigate('/login');
          break;
      }
    });

    return () => {
      axiosInstance.interceptors.response.eject(interceptorId.current as number);
    };
  }, []);

  return null;
};

const App = () => {
  return (
    <AuthProvider>
      <APIErrorProvider>
        <AppRoutes />
        <ResponseInterceptor />
        <APIErrorNotification />
      </APIErrorProvider>
    </AuthProvider>
  );
};
export default App;

-----------------------
import { useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { axiosInstance } from '../custom-axios';

export const ResponseInterceptor = () => {
  const { onLogout } = useAuth();
  const { addError } = useAPIError();
  const navigate = useNavigate()


  const interceptorId = useRef<number | null>(null);

  useEffect(() => {
    interceptorId.current = axiosInstance.interceptors.response.use(undefined, (error) => {
      switch (error.response.status) {
        case 401:
          navigate('/login');
          break;
      }
    });

    return () => {
      axiosInstance.interceptors.response.eject(interceptorId.current as number);
    };
  }, []);

  return null;
};

const App = () => {
  return (
    <AuthProvider>
      <APIErrorProvider>
        <AppRoutes />
        <ResponseInterceptor />
        <APIErrorNotification />
      </APIErrorProvider>
    </AuthProvider>
  );
};
export default App;

The unauthenticated git protocol on port 9418 is no longer supported

copy iconCopydownload iconDownload
    - name: Fix up git URLs
      run: echo -e '[url "https://github.com/"]\n  insteadOf = "git://github.com/"' >> ~/.gitconfig
git config --global url."https://github.com/".insteadOf git://github.com/
git config --global url."git@github.com:".insteadOf git://github.com/
-----------------------
    - name: Fix up git URLs
      run: echo -e '[url "https://github.com/"]\n  insteadOf = "git://github.com/"' >> ~/.gitconfig
git config --global url."https://github.com/".insteadOf git://github.com/
git config --global url."git@github.com:".insteadOf git://github.com/
-----------------------
    - name: Fix up git URLs
      run: echo -e '[url "https://github.com/"]\n  insteadOf = "git://github.com/"' >> ~/.gitconfig
git config --global url."https://github.com/".insteadOf git://github.com/
git config --global url."git@github.com:".insteadOf git://github.com/
-----------------------
git config --global url."https://".insteadOf git://
-----------------------
[remote "upstream"]
    url = git://github.com/curlconverter/curlconverter.git
    fetch = +refs/heads/*:refs/remotes/upstream/*
[remote "upstream"]
    url = git@github.com:curlconverter/curlconverter.git
    fetch = +refs/heads/*:refs/remotes/upstream/*
-----------------------
[remote "upstream"]
    url = git://github.com/curlconverter/curlconverter.git
    fetch = +refs/heads/*:refs/remotes/upstream/*
[remote "upstream"]
    url = git@github.com:curlconverter/curlconverter.git
    fetch = +refs/heads/*:refs/remotes/upstream/*
-----------------------
git config --global url."https://github".insteadOf git://github
Unhandled rejection Error: Command failed: /usr/bin/git submodule update -q --init --recursive
warning: templates not found /tmp/pacote-git-template-tmp/git-clone-a001527f
fatal: remote error:
  The unauthenticated git protocol on port 9418 is no longer supported.
Please see https://github.blog/2021-09-01-improving-git-protocol-security-github/ for more information.
fatal: clone of 'git://github.com/jquery/sizzle.git' into submodule path '/root/.npm/_cacache/tmp/git-clone-19674e32/src/sizzle' failed
Failed to clone 'src/sizzle'. Retry scheduled
warning: templates not found /tmp/pacote-git-template-tmp/git-clone-a001527f
-----------------------
git config --global url."https://github".insteadOf git://github
Unhandled rejection Error: Command failed: /usr/bin/git submodule update -q --init --recursive
warning: templates not found /tmp/pacote-git-template-tmp/git-clone-a001527f
fatal: remote error:
  The unauthenticated git protocol on port 9418 is no longer supported.
Please see https://github.blog/2021-09-01-improving-git-protocol-security-github/ for more information.
fatal: clone of 'git://github.com/jquery/sizzle.git' into submodule path '/root/.npm/_cacache/tmp/git-clone-19674e32/src/sizzle' failed
Failed to clone 'src/sizzle'. Retry scheduled
warning: templates not found /tmp/pacote-git-template-tmp/git-clone-a001527f
-----------------------
    insteadOf = ssh://
    insteadOf = git://
-----------------------
    insteadOf = ssh://
    insteadOf = git://

Vue &lt;script setup&gt; Top level await causing template not to render

copy iconCopydownload iconDownload
<script setup lang="ts">
import { apiGetInventory, GetInventoryResponse } from '@/module/inventory/common/api/getInventory';
import {ref, onBeforeMount} from 'vue';

const inventory = ref<GetInventoryResponse>()

onBeforeMount( async () => {
    inventory.value = await apiGetInventory()
})
</script>
-----------------------
<script setup lang="ts">
let inventory: GetInventoryResponse
const loadData = async () => inventory = apiGetInventory()
loadData()
</script>
<script setup lang="ts">
let inventory: GetInventoryResponse 
apiGetInventory().then(d: GetInventoryResponse => inventory = d)
</script>
-----------------------
<script setup lang="ts">
let inventory: GetInventoryResponse
const loadData = async () => inventory = apiGetInventory()
loadData()
</script>
<script setup lang="ts">
let inventory: GetInventoryResponse 
apiGetInventory().then(d: GetInventoryResponse => inventory = d)
</script>
-----------------------
import { apiGetInventory, GetInventoryResponse } from '@/module/inventory/common/api/getInventory'

let inventory = false
router.beforeResolve(async to => {
    // Skip if loaded or for specific vue file
    if (inventory || to.meta?.layout === 404 || to.meta?.layout === 'blank') {
        return
    }
    inventory = await apiGetInventory()
})

java.lang.NoSuchMethodError: No virtual method setSkipClientToken(Z)V in class Lcom/facebook/GraphRequest;

copy iconCopydownload iconDownload
implementation 'com.facebook.android:facebook-marketing:[4,5)'
implementation 'com.facebook.android:facebook-marketing:latest.release'
-----------------------
implementation 'com.facebook.android:facebook-marketing:[4,5)'
implementation 'com.facebook.android:facebook-marketing:latest.release'

Memory Leak in React component using useEffect

copy iconCopydownload iconDownload
  const isMountedRef = useRef();
  
  useEffect(() => {
    isMountedRef.current = true
    // In your async function check is the isMountedRef is true or not
    AxiosGetData("/jp-coin/featured", setFeatured);
    
    return () => { isMountedRef.current = false }
  }, []);
  const isMountedRef = useRef();
  
  useEffect(() => {
    isMountedRef.current = true;

    fetch('someAPIDomain').then(data => {
      isMountedRef.current && setState(data);
    });

    return () => { isMountedRef.current = false }
  }, []);
-----------------------
  const isMountedRef = useRef();
  
  useEffect(() => {
    isMountedRef.current = true
    // In your async function check is the isMountedRef is true or not
    AxiosGetData("/jp-coin/featured", setFeatured);
    
    return () => { isMountedRef.current = false }
  }, []);
  const isMountedRef = useRef();
  
  useEffect(() => {
    isMountedRef.current = true;

    fetch('someAPIDomain').then(data => {
      isMountedRef.current && setState(data);
    });

    return () => { isMountedRef.current = false }
  }, []);
-----------------------
  const handleClick = (item) => {
    if (item.type === 'news') {
      AxiosGetData(`/jp-coin/featured/${item.featuredId}`, setFeaturedById);
      setIsOpen(true);
    }
  };

Error: Must use import to load ES Module: D:\node_modules\react-markdown\index.js require() of ES modules is not supported

copy iconCopydownload iconDownload
{
  "name": "passportlegacy",
  "version": "0.1.0",
  "type": "module",
  "private": true,
  "scripts": {
    ...
  }
  ...
}
-----------------------
"dependencies": {
    "react-markdown": "^6.0.0"
  }
npm install 
-----------------------
"dependencies": {
    "react-markdown": "^6.0.0"
  }
npm install 

Cannot find name 'AbortSignal' during npm run build

copy iconCopydownload iconDownload
"lib": [
      "es2018",
      "DOM"
    ],

How do I get file names from a directory in a repository using Github API

copy iconCopydownload iconDownload
// If you don't send the path property, by default will send the contents from the root level
const repoContent = await github.rest.repos.getContent({
  owner: 'repo-owner',
  repo: 'repo-name'
});
  
console.log('Files found at root level', repoContent.data.map((file) => file.name));

Community Discussions

Trending Discussions on axios
  • Why items appends to the redux rather than replace?
  • Invalid options object. Dev Server has been initialized using an options object that does not match the API schema
  • React router v6 how to use `navigate` redirection in axios interceptor
  • The unauthenticated git protocol on port 9418 is no longer supported
  • Vue &lt;script setup&gt; Top level await causing template not to render
  • Z_DATA_ERROR, ERRNO -3, zlib: incorrect data check, MBA M1
  • java.lang.NoSuchMethodError: No virtual method setSkipClientToken(Z)V in class Lcom/facebook/GraphRequest;
  • Memory Leak in React component using useEffect
  • Error: Must use import to load ES Module: D:\node_modules\react-markdown\index.js require() of ES modules is not supported
  • Cannot find name 'AbortSignal' during npm run build
Trending Discussions on axios

QUESTION

Why items appends to the redux rather than replace?

Asked 2022-Apr-16 at 08:11

I'm newbie to Reactjs. The problem I'm encountered:

When Article page loads in the first time, all is fine and there are 10 articles shown. When I click on the browser back button, and then I go to the Article page for the second time, the article-list will be duplicated (so, it will be 20 articles). If I do so again, it will be 30 articles and so on ..

I want to know, why the result of API call appends for the Redux and not replace? In other word, how can I clean the Redux on page load every time? The expected result is seeing always 10 item (articles) on the page Article when I open it.


Here is a simplified of the element (for navigating to the list of articles) in the main page:

import Pages from "Constants/Pages";

const Component = () => {

    const history = useHistory();
    const navigateWithToken = (page) => {
        history.push(page);
      }
    };
    
    return (
        <div className="d-flex align-items-center flex-column py-1 ">
          <div
            className="main-footer-btn-article"
            onClick={() => navigateWithToken(Pages.Articles)}
          ></div>
          <span className="main-footer-btn-text">Articles</span>
        </div>
    )
};

export const ArticlesBtn = memo(Component);

Also, here is the Article page:

import { memo, useEffect } from "react";
import { useHistory } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";

import PostItems from "SharedComponents/PostItems";
import { getAllPosts } from "Redux/Actions";
import Pages from "Constants/Pages";

const Page = () => {
  const posts = useSelector((state) => state?.articles?.posts?.items);
  const dispatch = useDispatch();
  const { push } = useHistory();
  useEffect(() => {
    dispatch(getAllPosts());
  }, []);

  const onClickPost = (item) => {
    push({
      pathname: Pages.SingleArticle,
      state: {
        postId: item.id,
        title: item.subject,
        is_saved: item.is_saved,
      },
    });
  };

  return (
    <div className="full-height overflow-auto">
      { 
        posts?.map((item, index) => {
          return (
            <PostItems
              {...item}
              key={item.id}
              index={index}
              onClickPost={() => onClickPost(item)}
            />
          );
        })
      }
    </div>
  );
};

export default memo(Page);

Also here is the API call:

const getAllPosts = (page = 1) => {
  return async (dispatch: ReduxDispatch) => {
    //"posts?for=for_website"
    dispatch(toggleLoading(true));
    try {
      const { data } = await axios({
        method: "GET",
        url: "posts?for=for_mobile",
        params: { page: page },
      });
      const items = data?.data?.data;
      const pagination = {
        current_page: data.data.current_page,
        last_page: data.data.last_page,
      };
      dispatch(
        dispatchItemToRedux({
          type: ReducerTypes.GET_ALL_POSTS,
          payload: {
            items,
            pagination,
          },
        })
      );
    } catch (err) {
      return Promise.reject(err);
    } finally {
      dispatch(toggleLoading(false));
    }
  };
};

Also, here is the reducer:

import ReducerTypes from "Redux/Types/ReducerTypes";

const INITIAL_STATE = {
    posts: {
        items: [],
        pagination: {}
    },
    singlePost: {
        id: null,
        subject: null,
        caption: null,
        deep_link: null,
        short_link: null,
        total_comments: null,
        total_likes: null,
        total_views: null,
        created: null,
        medias: null,
        likes: [] 
    },
    postComments: []
};

function articleReducer(state = INITIAL_STATE, action) {
    switch (action.type) {
        case ReducerTypes.GET_ALL_POSTS:
            return {
                ...state,
                posts: {
                    items: state.posts.items.concat(action.payload.items),
                    pagination: action.payload.pagination
                }
            };
        case ReducerTypes.GET_SINGLE_POST:
            return {
                ...state,
                singlePost: action.payload
            };
        case ReducerTypes.GET_POST_COMMENTS:
            return {
                ...state,
                postComments: action.payload
            };
        case ReducerTypes.GET_POST_LIKES:
            return {
                ...state,
                singlePost: {
                    ...state.singlePost,
                    likes: action.payload
                }
            };
        default:
            return state;
    };
};
export default articleReducer;

ANSWER

Answered 2022-Apr-16 at 08:11
case ReducerTypes.GET_ALL_POSTS:
            return {
                ...state,
                posts: {
                    items: action.payload.items,
                    pagination: action.payload.pagination
                }
            };

Try omitting that .concat()

Source https://stackoverflow.com/questions/71892118

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install axios

You can use Gitpod an online IDE(which is free for Open Source) for contributing or running the examples online.

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Share this Page

share link
Consider Popular Reactive Programming Libraries
Compare Reactive Programming Libraries with Highest Support
Compare Reactive Programming Libraries with Highest Quality
Compare Reactive Programming Libraries with Highest Security
Compare Reactive Programming Libraries with Permissive License
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.