In the Alt Actions code below, how can I call getCharacters() after success of addCharacter? Basically I am trying to refresh list of characters after saving a new record to database.
getCharacters() {
requestPromise('http://localhost:3100/api/characters')
.then((res) => {
console.log("Getting Characters");
var opdata = JSON.parse(res);
this.actions.getCharactersSuccess(opdata.characters);
}).catch((err) => {
console.log('error:', err);
this.actions.getCharactersFail(err)
})
}
addCharacter(data) {
var options = {
method: 'POST',
uri: 'http://localhost:3100/api/characters/add/',
json: true,
body: {
name: data.charName,
allegiance: data.charAllegiance,
},
};
requestPromise(options)
.then((res) => {
// How can I recall getCharacters() from here
}).catch((err) => {
console.log('error:', err);
})
}
STORE
getCharactersSuccess(res) {
this.setState({
characters: res
})
}
This doesn't look right.It would be better if are you using any architecture like flux or redux. Any way you can do it buy just callingreturn this.getCharacters();
. Which refers to the getCharacters() function inside your class. the key point you missed is return this. which select the correct reference And the error occurs when you create a promise inside a promise scope, but you don't return anything from that Promise scope. So return will fix your issue.
addCharacter(data) {
var options = {
method: 'POST',
uri: 'http://localhost:3100/api/characters/add/',
json: true,
body: {
name: data.charName,
allegiance: data.charAllegiance,
},
};
requestPromise(options)
.then((res) => {
return this.getCharacters();
}).catch((err) => {
console.log('error:', err);
})
}