What is the best way to achieve this?
const func = (newPermissions) => {
this.setState({
permissions: { ...newPermissions }
},
() => {
if (this.state.permissions.read) {
// If we get here then func should return the result of an api call
// Currently the return just returns from callback of setState and func returns nothing
return api.getInfo().then((response) => {
return response;
});
}
});
}
I tried directly returning from the callback but it just returns from the callback of setState and func returns nothing.
Update: Potential Solution
Would this be a potential solution?
const func = (newPermissions) => {
return new Promise(resolve => {
this.setState({
permissions: { ...newPermissions }
},
() => {
if (this.state.permissions.read) {
resolve(api.getInfo().then((response) => {
return response;
}));
}
});
});
}
CodePudding user response:
No other way than using a promise
const func = (newPermissions) => {
return new Promise(resolve => {
this.setState({
permissions: { ...newPermissions }
},
() => {
if (this.state.permissions.read) {
return api.getInfo().then((response) => {
resolve(response);
});
}
});
});
}
Or another callback
const func = (newPermissions, callback) => {
this.setState({
permissions: { ...newPermissions }
},
() => {
if (this.state.permissions.read) {
return api.getInfo().then((response) => {
callback(response);
});
}
});
}