V
V
vertically-challenged2022-01-08 11:44:29
redux
vertically-challenged, 2022-01-08 11:44:29

Why do we need redux-thunk?

Why do we need redux-thunk?

I looked at a course on Redux, where an example of working with asynchronous code using thunk was given , but why is it needed if the same code can be described without it?

Here is an example with thunk:

//...

const asyncIncrementHandler = () => {
    return (dispatch) => {
        setTimeout(() => {
            dispatch({type: 'ASYNC_INCREMENT'})
        }, 5000);
    }
}

//...

<Button onClick={() => {
    dispatch(asyncIncrementHandler())
}}>ASYNC INCREMENT</Button>

//...


The same functionality, but without the thunk:

//...

const asyncIncrementHandler = (dispatch) => {
    setTimeout(() => {
        dispatch({type: 'ASYNC_INCREMENT'})
    }, 5000);
}

//...

<Button onClick={() => {
    asyncIncrementHandler(dispatch)
}}>ASYNC INCREMENT</Button>

//...


Why is this middleware needed, what is the use of it?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question