Home>

I have registration and authorization logic in my application

There is this code:

This is the function I call on the onSubmit button when I login

import store from "redux/store";
export const login= async (data)=> {
 try {
    const res= await api.login(data);
    if(res.status < 300)
        store.dispatch(setUserData(res.data))
    }
 } catch(err) {
    alert(err)
 }
}

How does this dispatch method differ from the one using redux-thunk?

export const loginAction= (data)=> async(dispatch)=> {
    try {
    const res= await api.login(data);
    if(res.status < 300)
        dispatch(setUserData(res.data))
    }
 } catch(err) {
    alert(err)
 }
}

Is there any difference at all? And if so, what is the best way to use it and why? Why does redux strongly recommend using tools like the redux-thunk middleware, because my actions are already asynchronous, I only dispatch when I receive a response from the server?

Here they explain why this is necessary (14:30, approximately). And you also have a check for the status of the response code, but this makes no sense, because if there is an error, it will simply execute the catch block + 400, 500 codes are also greater than 200)

ДимаЭф2022-01-23 14:47:55

@DimaEf, with the status code there is a typo, there should be res.status < 300, and the video does not say why we should pass the function to dispatch so that dispatch can be used from action if this can be done without middleware.

user4694852022-01-23 15:08:59

Then look here. And you, in theory, do not need to check the status of the code.

ДимаЭф2022-01-23 15:27:34