Reputation: 2031
I have a simple function to log out (just for testing) and I would like to inform the user when the action is completed. First that came in mind is to do this with promises.
I tried like this but there is something wrong with it. I don't quite understand how these works. Am I able to do it like this or would there be a better approach?
Function
logOut = () => {
this.props.logoutUser().then((passed) => {
if (passed) {
alert("You are now logged out!");
}
});
};
Logout action
export function logoutUser() {
return dispatch => {
new Promise(function (resolve, reject) {
dispatch(logout()).then((response) => {
return true;
}).catch((error) => {
return false;
});
});
}
}
function logout() {
return {
type: "LOGOUT"
}
}
Upvotes: 1
Views: 590
Reputation: 1015
you can also do this with callback
, like so -
logOut = () => {
this.props.logoutUser(result => {
if (result.success) {
alert("You are now logged out!");
return;
}
// Handle error
});
};
export function logoutUser(callback) {
logout()
.then(() => callback({ success: true }))
.catch(error => callback({ error }));
return dispatch => {
dispatch({
type: "LOGOUT"
});
};
}
function logOut() {
// log out function that returns a promise
}
Upvotes: 0
Reputation: 1515
Problem with Logout function
export function logoutUser() {
return dispatch => {
new Promise(function (resolve, reject) {
dispatch(logout()).then((response) => {
resolve(true); // changed
}).catch((error) => {
reject(error); // changed
});
});
}
}
you have to pass callback function resolve
for success, and reject
for fail.
refer this link
Update : and secondly you have to use thunk
middleware, to work dispatch
like Promise
object : github
Upvotes: 1