Ali
Ali

Reputation: 1759

How to have a separated js file that handles the API calls in Reactjs

I want to structure my react project and set my APIs and methods that makes the calls in a separate file. I am coming from Angular background, in Angular there are services which handle all http calls.

So, assume that i have a functional component called Supplier that have two files, Supplier.js and Supplier.css. I want to add a new file and call it SupplierServices.js in this file i want to write all methods that makes the calls to the server and simply import it in Supplier.js.

how to achieve this?

Upvotes: 3

Views: 8145

Answers (4)

Suraj Auwal
Suraj Auwal

Reputation: 318

You can do it like this 1. Create the method you want to export inside suppliers devices.js.

 SupplierServices.js
 Export const fetchData =  async () => {
 Const res =   await axios.get(your url) 
 Console.log(res) 
 }

2. Now import the fetchData method from supplierServices

Import { fetchData } from './SupplierServices'
Const Supplier = () => { 
 useEffect(.() =>{ 
 fetchData ()
 } )
}

Upvotes: 1

Piotr Żak
Piotr Żak

Reputation: 2132

i used to use flux architecture - this pattern can be use in every framework.

More info about implementing redux

   └─ client
      └─ redux
         └─ services
         └─ actions
         └─ reducers

Later encapsulating logic parts into individual parts (user.service, event.service, transaction service) etc.


Usually, event calls actions, which call service (in service promisses are operated asynchronously - try-catch), which return data(success) or error - that call the reducer and change the application's UI state (a bit complexity - but the advantage is the possibility of management all components - regardless of their relationality (global status).

Upvotes: 0

eMontielG
eMontielG

Reputation: 416

Components are just functions. You don't necesarily need to render anything in them, they can hold logic or API calls if you want. Before hooks, and when working without a state manager like Redux, you usually saw either HOCs (higher order components) or render props be used to compose logic together, here are some examples:

Using HOCs

Using hooks and render props

You can use hooks alone as well

There's also nothing stopping you from 'emulating' services like in your example, it's mostly a matter of taste and being aware of the pros and cons of each method.

Upvotes: 1

demkovych
demkovych

Reputation: 8857

Your file with request.js:

import axios from 'axios';

export default () => axios.get('/test');

Your component component.js:

import React from 'react';
import {request} from './request';

const Component = () => {
  .....
  request();
}

Upvotes: 6

Related Questions