简体   繁体   中英

Store.Dispatch() Resetting Redux Store

dispatch(action()) to trigger an action from outside my react component. It is working correctly in that it is triggering my action and updating the new item in my store. The problem is that it seems to be completely resetting everything else in my store, which to me at least makes it more of a problem than its worth.

Worth noting: I am using nextjs.

Here is a basic idea of my flow:

I have a utils folder with a service where I am dispatching this action from:

import store from './store';
store.dispatch(myAction());

I have my actions

export const myAction = () => ({
  type: HELP_ME,
  payload: true,
});

const initialState = {
  reducerVar: fase,
  otherExistingVar: {},
  otherExistingVarTwo: null,
  otherExistingThree:null,
  otherExistingVarFour: false,
};

const myReducer = (state = initialState, action) => {
  switch (action.type) {
    case HELP_ME: {
      const reducerVar = action.payload;
    } 
    default: {
      return state;
    }
  }
};
export default myReducer;

I am not sure if I am misusing store.dispatch() because I dont see why anyone would use this technique if it completely wipes out the existing data in the store. Or is there a better way to trigger this simple action from outside my component.

Basically I want to dispatch this action without completely wiping out my store just like I would dispatch the action if I were in a component.

Thank You!

What you are trying to do is fine. But your reducer must return the whole state with your change done by the action like below.

const myReducer = (state = initialState, action) => {
  switch (action.type) {
    case HELP_ME:
      const reducerVar = action.payload;
      return {...state, reducerVar }
    default:
      return state;
  }
};

you should return the state with value in reducer like this.

const myReducer = (state = initialState, action) => {
  switch (action.type) {
    case HELP_ME: {
      return {...state, reducerVar : action.payload}
    } 
    default: {
      return state;
    }
  }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM