7

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));

1 Answers1

6

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

Sagiv b.g
  • 30,379
  • 9
  • 68
  • 99
  • 4
    I think the OP meant to ask for a way to bind a hook to the redux-thunk action creator, not to do dispatches directly. – Carlos Jimenez Bermudez Aug 27 '20 at 22:11
  • @CarlosJimenezBermudez Thanks. Though the OP used the API in a wrong way, i just showed him/her the way this API should be use. Beside, the OP accepted the answer so i guess i did understand what the OP meant? – Sagiv b.g Aug 28 '20 at 08:28