Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to make async call in react-redux hooks with thunk?

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));
like image 418
Артём Котов Avatar asked Jan 30 '20 16:01

Артём Котов


People also ask

Is Redux thunk asynchronous?

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 .

What is async thunk in react?

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.

How do you handle async actions in Redux?

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.


1 Answers

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

like image 156
Sagiv b.g Avatar answered Oct 05 '22 12:10

Sagiv b.g