0

I am working on a react redux application where in, on a button click I need to change my window location. As of now, I am dispatching the button click action and trying to achieve the navigation in reducer using redux-loop.

Component js

class Component {
 constructor() {
  super()  
 }

 render() {
  return (
   <button onClick={() => this.props.onButtonClick()}>Navigate</button>
  )
 }

}

 const mapDispatchToProps = (dispatch) => {
    return {
        "onButtonClick": () => dispatch(handleClick())
    };
}

Action js

export const handleClick = () => ({
    type: NAVIGATE
});

Reducer js

export default (state = {}, action) => {
    if (action.type === NAVIGATE) {
        return loop(state, Cmd.run(navigateTo));
    }
};

Effect js

export const navigateTo = () => {
 window.location = "https://www.stackoverflow.com";
}

Apart from this action, I have lot many actions that involve side effect as well as state manipulation, hence redux-loop.

I have two questions:

  1. Control is not going into navigateTo() on button click. What am I doing wrong?

  2. I feel reducer is not a right place for it as we are not manipulating state here. What would be the best place to put this piece of code when button click action is dispatched?

ShailyAggarwal
  • 813
  • 9
  • 20
  • For number 2, which part are you saying should not be in the reducer? One of the core principles of redux-loop is that state changes are just one of many effects an action can have. So the reducer doesn't just decide what happens now due to a particular action, it decides what happens next. – bdwain May 19 '20 at 19:16
  • As per redux docs, Reducers specify how the application's state changes in response to actions, in my case I am just navigating to a new domain, should that window.href be in reducer? – ShailyAggarwal May 20 '20 at 07:03
  • i think the way you designed it is good. Side effects need to live in separate functions because they are called for you by redux loop, not called directly by the reducer. I've always found it helpful to put them in separate files so that they can be reused and tested independently – bdwain May 20 '20 at 15:30

1 Answers1

1

the code you have looks correct. Did you use the store enhancer when creating your redux store? Did you try setting a breakpoint in your reducer and verifying it gets called as you expect? https://redux-loop.js.org/docs/tutorial/Tutorial.html

bdwain
  • 1,665
  • 16
  • 35