Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to enforce redux action only dispatch once?

I am wondering how to flag redux action not dispatch the second time.

let triggerOnce = false;

export function populateStore() {
  return (dispatch) => {
    if (triggerOnce) return;

    dispatch({
      type: ReviewActions.UPDATE_REVIEW_STATE,
      data: review,
    });

    triggerOnce = true;
  };
}

as you can see right now i am using an external variable to flag... which is not that great. wondering if there is a better way. Thanks heaps for any suggestion

like image 417
Bill Avatar asked Oct 24 '25 17:10

Bill


1 Answers

I'm not exactly sure of your context so I apologize if I'm mistaken. I would attempt to find a way to only call the action once rather than set a flag in the global scope. If that's not desirable, you could set a flag in your reducer that is set to true once it's been populated.

const initialState = {
   hasBeenSet: false,
   ...restOfState,
}

const events = {
  [UPDATE_REVIEW_STATE]: (state) => {
     const { hasBeenSet } = state;

     return hasBeenSet ? state : { ...state, hasBeenSet: true };
  },
};

I hope that helps!

like image 167
John Luke Garofalo Avatar answered Oct 26 '25 05:10

John Luke Garofalo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!