Venkat
Venkat

Reputation: 65

Commonly API call for different components in ReactJS Fetch

I'm new to reactJS. How to commonly maintain fetch for all API call in one place. Only change URL and query string through passing parameter and get return data. LIKE THIS =>(In angular they maintained API in service.ts and make the call from component.ts and subscribe the return data.)

Upvotes: 1

Views: 2199

Answers (2)

There are different approaches, the easiest one (the one I used when started with React) is to use Axios (I prefer axios over fetch) and store all api calls in a service folder, for example, your project structure would be as follows:

react project
  src
    service
      service1.js
      service2.js

and a service would be as follows:

NOTE: I work this way because you may use certain service in multiple components, so if you need to fix something you just have to update your service

import axios from 'axios';

function getObjects() {
  return axios.get("http://yourservice/yourendpoint");
}

export {
  getObjects,
};

In your component you just import and use your service, depending on which approach you are using (old class stateful components or hooks)

import React from 'react';
import {getObjects} from './service/service1.js'

const MyComponent = () => {
    const [data, setData] = useState([]);

    useEffect(() => {
       getObjects().then(result=> setData(result.data));
    }, []);

    // use your sample
}

This is just an example, I think is a good starting point and you can improve the approach over time.

Greetings

Upvotes: 3

Piyush N
Piyush N

Reputation: 794

you can create a functional componet in react (Pass all the parameter to it.). Then you can call this in different components. Pure component in React is nothing but a java script function.

import axios from "axios";

export const getAll = function(url) {

    return fetch(url, {
      method: "get",
      headers: {
        "Content-Type": "application/json",
      },
    }).then(response => {
      if (!response.ok) {
        throw Error(response.statusText);
      }
      return response;
    });
};

Upvotes: 0

Related Questions