My project is using react, redux, and redux-thunk.
I want to wait for my function to end before launching a function that clear my page. Unofortunately i have a problem accessing my function in .then
Here was my previous code without promise and then :
this.props.dispatch(ScheduleAction(..))
this.props.deleteTab()
the problem was that sometime deleteTab() is called before sending the info to my server so not very good.
then i did :
Promise.resolve(this.props.dispatch(ScheduleAction(..)))
.then(function(response) {
this.props.deleteTab();
console.log("TabDeleted !!!");
return response
})
The problem now is that i can't access this.props.deleteTab();
And i have this as error :
Uncaught (in promise) TypeError: Cannot read property 'props' of undefined
If anyone have an idea on how to fix that by accessing props in .then, thanks in advance !!
My project is using react, redux, and redux-thunk.
I want to wait for my function to end before launching a function that clear my page. Unofortunately i have a problem accessing my function in .then
Here was my previous code without promise and then :
this.props.dispatch(ScheduleAction(..))
this.props.deleteTab()
the problem was that sometime deleteTab() is called before sending the info to my server so not very good.
then i did :
Promise.resolve(this.props.dispatch(ScheduleAction(..)))
.then(function(response) {
this.props.deleteTab();
console.log("TabDeleted !!!");
return response
})
The problem now is that i can't access this.props.deleteTab();
And i have this as error :
Uncaught (in promise) TypeError: Cannot read property 'props' of undefined
If anyone have an idea on how to fix that by accessing props in .then, thanks in advance !!
Share Improve this question asked Apr 19, 2018 at 10:25 foufrixfoufrix 1,4664 gold badges22 silver badges49 bronze badges 1-
have you tried of defining
this.props
outside of yourpromise
? Or you can also passthis.props
as parameter in your.then()
function parameter. – Nah Commented Apr 19, 2018 at 10:32
3 Answers
Reset to default 10Try this. You don't have access to this inside then. If you use arrow methods as below, you should be able to access it.
Promise.resolve(this.props.dispatch(ScheduleAction(..)))
.then((response)=> {
this.props.deleteTab();
console.log("TabDeleted !!!");
return response
})
The problem you have here is that you lost the context of this
keyword, which means this
now is undefined.
Since you can access this.props
outside the promise, what you want is to bind
this
inside your promise
function by doing smth like this
Promise.resolve(this.props.dispatch(ScheduleAction(..)))
.bind(this)
.then(function(response) {
this.props.deleteTab();
console.log("TabDeleted !!!");
return response
})
hope this method work for you
const $this = this;
const { dispatch } = this.props;
Promise.resolve(dispatch(ScheduleAction(..)))
.then(function(response) {
$this.deleteTab();
console.log("TabDeleted !!!");
return response;
})