I have a react component that, on load, gets a list of 'issues' from an api endpoint. It then displays them in a table. When an element is clicked, it sends a POST request telling that server that the issue has been resolved. This all works fine, but now, if the POST request returns 200, I need it to remove that issue from the state (and therefore from the table). I've tried the code below, but it says that it can't read the property 'state' of undefined, on the line this.state.issues
, suggesting that it doesn't know what 'this' is.
class IssueScreen extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
fetch(`${apiRoot}/${this.props.match.params.id}`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Token ${this.props.auth.token}`
}
})
.then(response => response.json())
.then(response =>
this.setState({
id: response.id,
issues: response.issues
})
);
}
resolveIssue(issueID) {
fetch(`${apiRoot}resolve_issue/`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Token ${this.props.auth.token}`
},
body: JSON.stringify({
id: issueID
})
}).then(function(res) {
if (res.status === 200) {
for (var i = 0; i < this.state.issues.length - 1; i++) {
if (this.state.issues[i].id === issueID) {
this.setState({ issues: this.state.issues.splice(i, 1) });
}
}
} else {
console.log("Problem");
}
});
}
The resolveIssue
is called by:
this.resolveIssue(id);
further on in the code.