DEV Community

Mayar Deeb
Mayar Deeb

Posted on

API services in React or Vue using Rxjs

- Explained About

  1. What is Service in Angular ?
  2. why Rxjs ?
  3. How to Create Service in React or Vue
  4. How to use Service in React component

1. What is Service in Angular ?

Services are a great way to share information among classes that don't know each other. by using services you'll be able to

  • fetch data form any component in your app
  • use Rxjs operators and others.....
  • use it as State management ( using subjects)
  • and have a clean and beautiful code

why Rxjs

RxJS can be used with any frameworks or Pure Javascripta .
that's mean the following code works on Vue.js or vanilla

RxJS is a library for composing asynchronous and event-based programs by using observable sequences

RxJS offers a huge collection of operators in mathematical, transformation, filtering, utility, conditional, error handling, join categories that makes life easy when used with reactive programming.

3. How to Create Service in React or Vue

  1. install the following library's
$ npm install axios rxjs axios-observable
Enter fullscreen mode Exit fullscreen mode
  1. create a folder to contain all of your api services, usually i name it services
    and I also create it in src/srvices, it doesn't matter create it where every you want.
    Image description

  2. create new .ts or .js file, i'll name it task.ts (because am using typescript here)

import Axios, { AxiosObservable } from "axios-observable";

class TaskService {

    private static _instance: TaskService;

    public static get Instance() {
        return this._instance || (this._instance = new this());
    }

/////...code here

}


export const _TaskService=TaskService.Instance;

Enter fullscreen mode Exit fullscreen mode

so here we create singleton class so we can use Subjects later also it's better than making an object of the class in each component.

3.write your api calls, I'll write a simple CRUD

import Axios, { AxiosObservable } from "axios-observable";

class TaskService {

    private static _instance: TaskService;

    public static get Instance() {
        return this._instance || (this._instance = new this());
    }

  indexTask():AxiosObservable<any> {
   return Axios.get<any(`https://example.com/api/index`);
    }

  showTask(id:number):AxiosObservable<any> {
   return Axios.get<any(`https://example.com/api/show/${id}`);
    }

  storeTask(data:any):AxiosObservable<any> {
   return Axios.post<any(`https://example.com/api/store`,data);
    }

  updateTask(id:number,data:any):AxiosObservable<any> {
   return Axios.put<any(`https://example.com/api/update/${id}`,data);
    }

  deleteTask(id:number):AxiosObservable<any> {
   return Axios.delete<any(`https://example.com/api/delete/${id}`);
    }

}




export const _TaskService=TaskService.Instance;

Enter fullscreen mode Exit fullscreen mode

and we are done here.

4. How to use Service in React component

import { useEffect, useState } from "react";
import { _TaskService } from "src/services/Task.Service";

const Tasks = () => {

  const [tasks, settasks] = useState([]);

  useEffect(() => {

    _TaskService.indexTask().subscribe({
      next: (res) => settasks(res.data),
      error: (err) => console.log(err.response),
      complete: () => {},
    });

    return () => {};
  }, []);

  return (
    <div>
      {tasks.map((task: any, index: number) => {
        return <div key={index} > {task.name} </div>;
      })}
    </div>
  );
};

export default Tasks;


Enter fullscreen mode Exit fullscreen mode

the end....

if you are an Angular developer who is switching to React or Vue am sure you'll be happy to find this.

if you are not, then I suggest you to read about Rxjs especially Subjects and Operators.

useful links 🔗

https://rxjs.dev/

GitHub logo zhaosiyang / axios-observable

Use axios in a rxjs way. use Observable instead of Promise

axios-observable

Observable (as opposed to Promise) based HTTP client for the browser and node.js

Want to use axios in a rxjs (observable) way? There we go!

This API of axios-observable is almost same as API of axios, giving you smooth transition. So the documentation mirrors the one of axios (A few exceptions will be cleared pointed out).

Features

  • Make XMLHttpRequests from the browser
  • Make http requests from node.js
  • Supports the Observable API
  • Intercept request and response
  • Transform request and response data
  • (NEW in v1.1.0) Cancel requests through unsubscribe
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

Installing

Using npm note: axios and rxjs are peer dependencies.

$ npm install axios rxjs axios-observable
Enter fullscreen mode Exit fullscreen mode

Example

Performing a GET request

import Axios from  'axios-observable';
// or const Axios = require('axios-observable').Axios;
// Make a request for a user with a given ID
Axios.get('/user?ID=12345')
  .
…
Enter fullscreen mode Exit fullscreen mode

.

Top comments (0)