admin管理员组文章数量:1395893
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.
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.
- You should perform saveAction when validate happens, and use that to modify both isValid variable and other variables in reducers. No real use in waiting for isValid variable to be set to true. – Bhargav Ponnapalli Commented Apr 24, 2016 at 15:04
- @bhargavponnapalli the problem is second action is async (react-thunk), so it can't be just bined with first. – xander27 Commented Apr 24, 2016 at 15:17
- You can perhaps validate within the async action, instead of a separate validate action. Just an idea. – Bhargav Ponnapalli Commented Apr 24, 2016 at 15:59
- Not an answer to the question but a friendly tip: As you're using Redux I'd strongly remend you taking a look at Redux Sagas ( github./yelouafi/redux-saga ). It's a small learning curve but once you got a hang of it you'll be creating async/sync actions in no time. – Emil Oberg Commented Apr 24, 2016 at 18:56
2 Answers
Reset to default 5There 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 ment, 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
}
本文标签: javascriptRedux call action after other action if conditionStack Overflow
版权声明:本文标题:javascript - Redux call action after other action if condition - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744123441a2591847.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论