简体   繁体   中英

How to return a promise from redux thunk action and consume it in component

I am using React+Redux+Redux Thunk + Firebase authentication. Writing code in Typescript. My action is:

//Type for redux-thunk. return type for rdux-thunk action creators
type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  IStoreState, //my store state
  null,
  Action<userActionTypes>
>

export const signInWithEmailAndPasword =(email:string, pasword:string): AppThunk=>{
  return async (dispatch)=>{
    auth.signInWithEmailAndPassword(email, pasword).then(response=>{
      if(response.user){
        const docRef = db.collection("users").doc(response.user.uid);
          docRef.get().then(function(doc) {
            if (doc.exists) {
              const userData = doc.data(); //user data from firebase DB
               //if user exists in DB, dispatch
               dispatch({
                type: userActionTypes.SIGN_IN_USER,
                payload: userData
              })
              return userData;
            } else {
                // doc.data() will be undefined in this case
                console.log("No such document!");
            }
        }).catch(function(error) {
            console.log("Error getting document:", error);
        });
      }
    })
    .catch(err=> dispatch(setUserError(err.message)))
  }
}

My SignIn component, where i am dispatching this above action:

import React, { useState } from 'react'
//some other imports
//...
//
import { useDispatch, useSelector } from 'react-redux';
import { signInWithEmailAndPasword } from '../../redux/actions/userActions';


interface ISignInState {
  email: string;
  password: string;
}
const SignIn = (props:any) => {

  const [values, setValues] = useState<ISignInState>({ email: '', password: '' })

  const dispatch = useDispatch();

  const handleInputChange = (e: React.FormEvent<HTMLInputElement>): void => {
    const { name, value } = e.currentTarget;
    setValues({ ...values, [name]: value })
  }

  const handleFormSubmit = (e: React.FormEvent) => {
    e.preventDefault()
    const { email, password } = values;
    dispatch(signInWithEmailAndPasword(email, password))
//// -> gives error: Property 'then' does not exist on 
//// type 'ThunkAction<void, IStoreState, null, Action<userActionTypes>>'
    .then(()=>{ 
      props.history.push('/');
      setValues({ email: '', password: '' })
    })

  }

  return (<div>Sign in UI JSX stuff</div>)

So when i try to use .then() after dispatch(signInWithEmailAndPasword(email, password)) it gives an error Property 'then' does not exist on type 'ThunkAction<void, IStoreState, null, Action<userActionTypes>>' So how can i return promise from redux action and chain a .then() on it? I always assumed that thunk actions return promises by default. Thanks for your help Edit: Temporary soluton was to use any as return type of above action:

export const signInWithEmailAndPasword = (email:string, pasword:string):any =>{
  return async (dispatch: any)=>{
    try {
      const response = await auth.signInWithEmailAndPassword(email, pasword)
      if(response.user){
        const userInDb = await getUserFromDB(response.user)
        dispatch(userSignIn(userInDb))
        return userInDb
      }
    } catch (error) {
      dispatch(setUserError(error.message))
    }
  }
}

But I don't want to use any

Just add return before this line:

auth.signInWithEmailAndPassword(email, pasword).then(response=>{

So it would be:

export const signInWithEmailAndPasword =(email:string, pasword:string): AppThunk=>{
  return async (dispatch)=>{
    return auth.signInWithEmailAndPassword(email, pasword).then(response=>{

It should work.

AppThunk<Promise<void>>


You need to explicitly declare the AppThunks return type, which in this case should be a Promise containing nothing. You have already made it async so just make sure to enter the correct AppThunk return type

export const signInWithEmailAndPassword = (email: string, password: string): AppThunk<Promise<void>> => {
  return async (dispatch) => {
      // do stuff
  }
}

Thunks return functions, not promises. For this you could look at redux-promise . But to be honest if your doing something this complex you would be much better off using redux-saga .

Another approach would be to use the concepts behind redux-api-middleware to create your own custom redux middleware. I have done this in the past to connect a message queue to redux.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM