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.
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
}
};
}
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With