There are following ways of component communication in react:
- From Parent to Child using Props
- From Child to Parent using Callbacks
- Between Siblings :
- Combine the above two methods
- Using Redux
- Using React’s Context API
But, What if you don't want to use the context API hook?
What if you want to minimize API calls from listing to detail components?
What if you want the communication of unrelated components?
Here comes the service that actually holds data on the trigger and passes it to the desired data requested components.
you have to make a shared service, using exported class in react,
class dataHolding {
constructor() {
this.data = {};
}
getData(data) {
this.data = data;
console.log(data);
}
setData() {
return this.data;
}
}
export default new dataHolding;
calling dataHolding service to store data,
// Component A
this.dataHolding.getData(data);
calling dataHolding service to retrieve data from service anywhere,
// Component B
let details = this.dataHolding.setData();
Top comments (3)
Hi,
I have a question regards this.if I am wrong sorry.i am new in react, the question is without import component how you can access methods above example
// Component A
this.dataHolding.getData(data);
// Component B
let details = this.dataHolding.setData();
can you please give Component A code
absolutely as you said, after import I got the access to call the method of that class in the component. without we can't use the class or component in other component.
Using Rxjs Subscribers way the service will look likes:
import { Subject } from 'rxjs';
const subject = new Subject();
export const dataService = {
setData: d => subject.next(d),
clearData: () => subject.next(),
getData: () => subject.asObservable()
};