Angger
Angger

Reputation: 805

Getting dispatch function return value

I'm new to react. I tried to separate component and action function. but I cannot get return value from separate action function. Is it possible to return a value (e.g Object {}) from dispatch function

I put the brief code as below :

LoginComponent.js

class Login extends React.Component {
   constructor(props){
      super(props)
      this.state = {
         username : '',
         password : ''
      }
   }
   submit = (e) => {
      /* console.logging "Some response"*/
      console.log(this.props.doLogin(this.state))
   }
   render(){
      return (
         <form onSubmit={this.submit}>/* some login element */</form>
      )
   }
}

export default connect(null, {LoginAction})(Login);

LoginAction.js

export function doLogin(state){
   return dispatch => {
      return axios.post('login', state).then(res =>{

      return "Some response";

    })
   }
}

but It doesn't return any value

Thankyou.

Upvotes: 19

Views: 43911

Answers (3)

Tapendra kumar
Tapendra kumar

Reputation: 93

You can use callback function

this.props.doLogin((this.state),(result)=>{
  console.log(result)
})

export function doLogin(state,callback){
   return dispatch => {
      return axios.post('login', state).then(res =>{

      callback(res);

    })
   }
}

Upvotes: 5

casieber
casieber

Reputation: 7542

Contrary the the above answer, you actually can return whatever you want from a thunk. Redux-thunk will pass it through.

In your case, where your thunk is returning a Promise<string>, that means that in your component this.props.doLogin(this.state) will also evaluate to a Promise<string>.

So instead of trying to log the Promise, instead try switching that log code over to this.props.doLogin(this.state).then(result => console.log(result);

Upvotes: 11

simbathesailor
simbathesailor

Reputation: 3687

Returning the function is not an option when you are using redux-thunk. it will run the callback and dispatch whatever you pass as an action object. So as you want to make the api call ans see whether it is a success or failure . You need to dispatch and action on success. save it in redux state. and access the data in your component

export function doLogin(state){
   return dispatch => {
      axios.post('login', state).then(res =>{
       dispatch({
        data:  "Some response",
        type: "API_SUCCESS"
       })
       })
       .catch(err) {
       dispatch({
        data:  err,
        type: "API_FAILURE"
       })
       }
}

And then access those values in your component like this

mapStateToProps = (state) => ({
data: state.yourreducer.data,
})
define mapDispatchToProps if you need dispatcch binded functions
export default(mapStateToProps, mapDispatchToProps)(YourComponent)

Upvotes: 1

Related Questions