A quick and easy way to share data between two components using RxJS.
In this case we’ll use an RxJS service to increment a number in two components.
npm install rxjs --save
Create a file called numberService.js and add the following
import {Subject} from 'rxjs';
const subject = new Subject();
export const numberService = {
updateNumber: message => subject.next(message),
clearNumber: () => subject.next(),
getNumber: () => subject.asObservable()
};
Setup your first component and display the value.
In this case we’ll use App.js for brevity
import './App.css';
import ComponentTwo from "./componentTwo";
import {numberService} from "./services/numberService";
import {useState} from "react";
function App() {
const [number, setNumber] = useState(0);
function updateService(e) {
numberService.getNumber().subscribe(n => {
if (n) {
// add message to local state if not empty
setNumber(n);
} else {
setNumber(1);
}
});
numberService.updateNumber(number + 1);
}
return (
<div>
{number}
<button onclick="{updateService}">
Increment number
</button>
<ComponentTwo />
</div>
);
}
export default App;
We’ll now subscribe to the service and display this value in your other component.
import {numberService} from "../../../services/numberService";
import {useEffect, useState} from "react";
function ComponentTwo() {
const [number, setNumber] = useState(0);
useEffect( () => {
numberService.getNumber().subscribe(n => {
if (n) {
setNumber(n);
}
});
}, [])
return (
<div>
<h1>{number}</h1>
</div>
);
}
export default ComponentTwo;
When you update the data in this service by clicking the button, the value will automatically update in all components that are subscribed to it.