I trying to use rxjs inside a functional component's useEffect Hook.
I believe useEffect can be used just like componentDidMount and componentDidUpdate.
const Counter = () => {
const [state, setState] = useState({counter: 0});
useEffect(() => {
subscriber.subscribe((value) => {
let { counter } = state;
counter += value;
setState({ counter });
});
});
return (
<div>
<span>Counter: {state.counter}</span>
<Crementer />
</div>
);
The subscriber is a simple rxjs subject
const subscriber = new BehaviorSubject(0);
There's also a component to increment / decrement the counter
const Crementer = () => {
return(
<>
<button onClick={() => subscriber.next(1)}>+</button>
<button onClick={() => subscriber.next(-1)}>-</button>
</>
)
};
(I tried counterService.send(1) as well)
The problem is as soon as I click + or - the counter increments or decrements continuously.
You can see the behavior here: https://stackblitz.com/edit/react-9auz4d
Maybe because useEffect runs also on update? It will probably work in a class component with a componentDidMount() ?