API services in React or Vue using Rxjs
Tags: react, angular, rxjs, vue
Published: 2022-04-12 22:10:29

## - 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
```

2. 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6ls1t8ktkrzb4s4boi3e.png)
 
3. create new `.ts` or `.js` file, i'll name it `task.ts` (because am using typescript here)

```typescript 
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;

```
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`


```typescript 
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;

```
and we are done here. 

## 4. How to use Service in React component 

```react
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;


```
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/

{% embed https://github.com/zhaosiyang/axios-observable %}.