I starting to learn hooks. But i dont understand how right work with async call. Earlier i was use
import * as actionQR from "../actions/qr";
...
function mapDispatchToProps(dispatch) {
return {
actionQR: bindActionCreators(actionQR, dispatch),
}
}
and after this call my this.props.actionQR.myFunc()
, but what I should do with useDispatch()?
if I just call
import {foo} from "../actions/qr";
...
useDispatch(foo());
then my foo()
dont console.log(2)
export const foo = () => {
console.log(1);
return (dispatch) => {
console.log(2);
}
}
Im using thunk
import createRootReducer from './reducers/index';
...
const store = createStore(createRootReducer, applyMiddleware(thunk));
Thunk functions can be used for both asynchronous and synchronous logic. Thunks provide a way to write any reusable logic that needs access to dispatch and getState .
createAsyncThunk will generate three Redux action creators using createAction : pending , fulfilled , and rejected . Each lifecycle action creator will be attached to the returned thunk action creator so that your reducer logic can reference the action types and respond to the actions when dispatched.
Using Thunk and Redux Toolkit to manage asynchronous actions The role of this middleware is very simple: verify if an action is a function and, if it is, execute it. This simple behavior allows us to create actions not as simple objects, but as functions that have business logic.
The useDispatch()
hook will return a reference to the dispatch
function, you don't pass to it an action, you get the dispatch
reference and pass to it (the dispatch
) the action.
So basically it should look something like this:
const dispatch = useDispatch()
dispatch(foo())
You can get more details from the react-redux DOCS
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