1

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.)

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your answer.this method works for me.Actually i searched the reference in many sites.But that didn't fulfill my expectation.Thank you.
0

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;
    });
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.