how do I make axios API call in a separate component / file?

Viewed 15229

How do I make axios API call in a separate component / file?

example:

I created the index.jsx file that contains the component to integrate axios and after that I created the app.jsx file to render the index.jsx file containing axios in the index.jsx file

thanks before

2 Answers

You can create a separate folder api for all APIs:

Let's say you have AuthenticationAPI, you have to something like this:

AuthenticationAPI.js

import axios from 'axios';

export const onAuthenticate = payload => {
  const URL = `YOUR_URL`;
  return axios(URL, {
    method: 'POST/GET',
    headers: {
      'content-type': 'application/json', // whatever you want
    },
    data: payload,
  })
    .then(response => response.data)
    .catch(error => {
      throw error;
    });
};

in you App.js

import * as AuthenticateAPI from 'api/AuthenticationAPI';

 // in your CDM
 componentDidMount(){
  AuthenticateAPI.onAuthenticate(payload).then((res)=>{ //any payload you want to send just for example
    you can get response here in then block
 }) 
 }

This is for the sake of basic example. You can use redux if it becomes the NECESSITY Otherwise don't abuse it.

PS: Axios is built on cancellable promise pattern. It has it's abort controller. In short you can cancel any pending network call which is an great alternative to use Observable. Cancel API calls is really important sometimes when you don't really need the data while navigation to another page in between ongoing API request so the data is useless and AXIOS is the lone savior.

You can import functions / methods on the fly using export

Create a shared.js file. for example call it: apicalls.js

inside write your functions as so:

apicalls.js

import axios from 'axios';

export function getData(config, callback, errorcallback){
    axios.get(url, config)
    .then(res => {
      //do something
      if(callback != null){
         callback(res);
      }
    })
    .catch(err => {
      // catch error
      if(errorcallback != null){
         errorcallback(err);
      }
    })
}

In any component, use as follows

// get the location of your apicalls.js file and use to import like below
import { getData } from '../../routetothisjsfile'


//use it 
var config = { "Access-Control-Allow-Origin": "*" }
getData(config, (res) => {
    //success
},(err) => {
    //error
    alert(err);
});
Related