Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to listen to certain action in redux

Tags:

reactjs

redux

I am using React and Redux (react starter kit).

I have a set of action, and when some are called, I want to dispatch side effects.

For exemple, I have a workspace that contains projects, if workspaceID in the store change, (using my action setWorkspaceId) then, the projects store will notice the change, and start execute some api call to update itself.

IN angular/ngrx, I was using Effects, so the Effect where dispatching other action when a certain action was called.

What is the redux way ? I was checking into Redux-Saga, but is there something else or already built in ?

like image 727
Bobby Avatar asked Dec 23 '22 20:12

Bobby


2 Answers

Left alone, Redux just accumulates state from the actions it receives via dispatch, so there is no single Redux-blessed way to trigger side effects from actions.

But it supports middleware, which allows you to monitor, subscribe to and even change actions that are dispatched.

If you're familiar with RxJS via ngrx, redux-observable might be something worth looking into. It allows you to consume and emit actions via RxJS's observable type. The use case you describe of triggering an API call when a value changes would be well-suited to this.

But as you say, there's also redux-saga, which uses generators to model asynchronous logic around the consumption and production of Redux actions and other side effects. There are pros and cons to these and all the other solutions out there.

Ultimately I suggest starting with what's most familiar to you, especially if you're new to Redux.

One piece of unsolicited advice - middleware is easy to overuse. Be wary of doing in middleware and side effects that which can be achieved in a reducer.

It's easy and tempting enough to set up middleware to dispatch action B in response to action A, but if all action B does is update some state, maybe that state's reducer can just react to action A.

like image 122
backtick Avatar answered Jan 09 '23 13:01

backtick


What is the redux way?

Use mapStateToProps to subscribe for store changes.

Then use useEffect in your function component, with workspaceID as dependency, to do some side effects (i.e calling an api).

function Component(props) {
  useEffect(
    () => {
      // call api
    }
    , [props.workspaceID] // only run effect when workspaceID changes
  )
}

mapStateToProps(state) {
  return {
    workspaceID: state.workspaceID // subscribe to workspaceID changes in store
  }
}

connect(mapStateToProps, {})(Component)
like image 28
Joseph D. Avatar answered Jan 09 '23 11:01

Joseph D.