0
votes

Follow the official doc, I make a login typescript like thunk function.

function loginApi(user: UserState) {
  return fetch(
    `${baseUrl}/login?user=${user.userName}&pwd=${user.pwd}`
  )
    .then(res => res.json())
}

export const thunkLogin = (
  user: UserState
): ThunkAction<void, AppState, null, Action<string>> => async dispatch => {
  const asyncResp = await loginApi(user)
  dispatch(
    updateUser({
      loggedIn: asyncResp.isloggedIn,
      userName: user.userName,
      userPwd: user.userPwd
    })
  )
}

I want add this thunk function to my app component using react-redux connect hoc function.

import { thunkLogin } from './thunkLoginPath'

interface Props {
  // place 1
  thunkLogin: typeof thunkLogin
}

interface State {
  userName: string
  userPwd: string
}

class AppComponent extends React.Component<Props, State> {
  handleSubmit = () => {
    this.props.thunkLogin({
      userName: this.state.userName,
      userPwd: this.state.userPwd
    })
  }

  render(){
    return(
      <TouchableOpacity
        style={style.loginBotton}
        onPress={this.handleSubmit}
      >
        <Text style={style.loginBottomText}>LOGIN</Text>
      </TouchableOpacity>
    )
  }
}

export default connect(
  (state: AppState) => ({
    user: state.user
  }),
  // place 2
  { thunkLogin }
)(AppComponent)

It report a error show that the thunkLogin declare at Props not assignable to mapDispatchToProps (place 1 -> place 2).

2

2 Answers

0
votes

did you mean to connect AppComponent or Login component, since you trying to call this.props.thunkLogin from AppComponent but you connect Login. try to change it like this.

export default connect(
  (state: AppState) => ({
    user: state.user
  }),
  // place 2
  { thunkLogin }
)(AppComponent)
0
votes

Your mapDispatchToProps is totally okay. If you want to use some other syntax here you have:

const mapDispatchToProps = (dispatch) => {
  return {
    thunkLogin: (user: UserState) => {
      dispatch(thunkLogin(user))
    }
  }
}

But I think that this won't help you with TypeScript errors. At least I had many many problems with react-thunk. I ended up throwing away all that ThunkAction crap since TypeScript is smart enough to recognize functions types. I only took care that nested function of action creator returns any. In reality it always returns void (but TypeScript doesn't like it). Your function would look something like this:

export const thunkLogin = (user: UserState) => async (dispatch): any => {
  const asyncResp = await loginApi(user)
  dispatch(
    updateUser({
      loggedIn: asyncResp.isloggedIn,
      userName: user.userName,
      userPwd: user.userPwd
    })
  )
}

This solution is good enough for me, because it shows me typing inside the component. I can be aware if action creator is regular or thunk-powered. An example: mapDispatchToProps example

If you want to read more about react-thunk and typescript, go here: https://github.com/reduxjs/redux-thunk/issues/103