V
V
Vasily Enshin2019-11-18 13:09:15
typescript
Vasily Enshin, 2019-11-18 13:09:15

Typescript + React + Redux + Thunk how to asynchronously call a function inside onSubmit?

There is a problem when calling the loginUser function on a form. Somewhere I write the function itself incorrectly and use dispatch, but authApi.login() is not called at all
Here is the code to make it "clear" what I mean

export type AuthActionType =
  | SetTokenAction
  | DeleteTokenAction
  | SetUserInfo
  | ResetUserInfo
  | GetUserInfo
  | Logout

export const loginUser = (values: SubmitValues): ThunkAction<Promise<void>, {}, {}, AuthActionType> => {
  return async (dispatch: ThunkDispatch<{}, {}, AuthActionType>): Promise<void> => {
    const userInfo = await authApi.login({
      email: values.email,
      password: values.password,
    })
    dispatch(setToken(userInfo.jwt))
    dispatch(getUserInfo())
  }
}

interface MapDispatchToProps {
  loginUser: (values: SubmitValues) => ThunkAction<Promise<void>, {}, {}, AuthActionType>
}

const mapDispatchToProps = (dispatch: Dispatch): MapDispatchToProps => ({
  loginUser: bindActionCreators(loginUser, dispatch),
})

const api: AuthApi = {
  login(loginData: LoginRequest, config: {}): Promise<LoginResponse> {
    console.log('LoginResponse', 'inlogin')
    return authnApi.post('/login', loginData, config).then(
      (response): LoginResponse => {
        return response.data
      },
    )
  },
}

export default api

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