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.
The dispatch function is the exact same function as React returned for the previous call to useReducer. The component sets up an event handler. This is a new version of the handler and may use some of the newly updated state values. The component returns its UI.
dispatch is a function of the Redux store. You call store. dispatch to dispatch an action. This is the only way to trigger a state change. With React Redux, your components never access the store directly - connect does it for you.
There are two ways to dispatch actions from functional components: Using mapDispatachToProps function with connect higher order component, same as in class based components. Using useDispatch hook provided by react-redux . If you want to use this hook, then you need to import it from the react-redux package.
dispatch() is the method used to dispatch actions and trigger state changes to the store. react-redux is simply trying to give you convenient access to it. Note, however, that dispatch is not available on props if you do pass in actions to your connect function.
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);
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);
})
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With