LiquidDeath
LiquidDeath

Reputation: 1828

How to keep rest api calls in different file in react js

I'm new to react js and have been building something which works absolutely fine. But as of now the api calls to be made are defined inside respective components. So if any changes to be made to the ip or endpoint, i need to make changes at every place. How can i separate all the api calls in one file and perform the operation on result in respective component file.

Below is an example :

import axios from "axios";

function get_all_user(){
axios({
      method: "get",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      url: "http://127.0.0.1:8000/app/users/",
    })
      .then(function (response) {
        console.log(response.data);
      })
      .catch(function (error) {
        console.log(error);
      })
      
}

function get_single_user(userid){

axios({
      method: "get",
      headers: { "Content-Type": "application/x-www-form-urlencoded" },
      url: "http://127.0.0.1:8000/app/users/"+userid,
    })
      .then(function (response) {
        console.log(response.data);
      })
      .catch(function (error) {
        console.log(error);
      })
      
}

in every component i have api calls to make. all these api calls needs to be at one place. Any help is appreciated.

Upvotes: 9

Views: 18452

Answers (2)

Sudarshan Rai
Sudarshan Rai

Reputation: 306

You can use axios instance method , you stetup your Api config in one file then import and use

/api.js

import axios from "axios";
export const axiosRequest = axios.create({
  baseUrl: "https://jsonplaceholder.typicode.com/"
});

/app.js

import React from 'react';
import { axiosRequest } from './api';
export default function App() {

  React.useEffect(()=>{
    axiosRequest.get('/todos/1')
    .then(res=>console.log(res))
    .catch(err=>console.log(res))
  },[])
  
  return <>axios</>
}

here is working code example: codesandbox

Upvotes: 0

Sowam
Sowam

Reputation: 1746

You can just move whole of this code into another component and add word export before function definition like:

export function get_all_user(){
  // rest of code
}

and then you just have to import that in your components

import { get_all_user } from './path/to/file/'

so you can use them in multiple files by:

get_all_user()

Here is an example, it text.js file you have exported function, in index.js file you just use it

Upvotes: 8

Related Questions