Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux call action after other action if condition

How should I implement in redux following logic: There a 2 actions: sync and async. Let say its validate() and save(). When user clicks buttons validate() performed and it changes some isValid variable in state store. Then if isValid save action performed.

like image 293
xander27 Avatar asked Feb 07 '23 04:02

xander27


2 Answers

There are many ways to do what you'd like. However, as a general rule, don't store anything in Redux that can be derived. isValid can be derived by running your validation on your field(s). Moreover, I don't think that intermediate state like form field values that are changing belong in Redux. I'd store them in React state until they're considered valid and submitted.

With that out of the way, as Spooner mentioned in a comment, you can call a sync action within a thunk. Or you can access state within the thunk.

Option #1

// Action Creator
export default function doSomething(isValid) {
    return (dispatch) => {

        dispatch(setValid(isValid));

        if (isValid) {
            return fetch() //... dispatch on success or failure
        }
    };
}

Option #2

// Component
dispatch(setValid(isValid));
dispatch(doSomething());

// Action Creator
export default function doSomething() {
    return (dispatch, getState) => {

        const isValid = getState().isValid;

        if (isValid) {
            return fetch() //... dispatch on success or failure
        }
    };
}
like image 52
Rick Jolly Avatar answered Feb 10 '23 23:02

Rick Jolly


You can 'wrap' those functions in 'click handler'.

//call it on button click

handleClick = () => {
  if (validate()) {
    //call save function
    save()
  }
}

validate = () => {
  //do something
  //check validness and then
  if (valid) return true 
}
like image 39
Spooner Avatar answered Feb 11 '23 01:02

Spooner