Reputation: 2231
I am really struggling with the state in the following code. I call a function with the 'onClick'. This function has been bounded in the constructor of the component, yet for some reason the 'this.function' in the eventhandler is returned as 'undefined'.
render() {
if (bla) {
(...)
return (
<div>Loading</div>
)
} else: {
return (
<div>
<a onClick={this.activeorArchive}><h4>Archive</h4></a>
</div>
}}
The onClick calls the following function.
activeorArchive() {
if (this.state.active === true) {
this.setState((prevState, props) => ({
assessments_list_url: prevState.assessment_list_url + 'archived=false' + "/"
}))
console.log(self.state.active)
} else {
this.setState((prevState, props) => ({
assessments_list_url: prevState.assessment_list_url + 'archived=true' + "/"
}))
console.log(self.state.active)
}
}
Its not clear to me what I am doing wrong here. I've had a somewhat simular problem in the past where the return statement was part of a function itself (which was solved by converting it to a arrow function). But surely there must be a way to retain the state in a if/else statement?
As requested, the constructor:
constructor(props) {
super(props);
this.state = {
assessments: '',
categories: '',
active: true,
assessments_list_url: "/api/assessments/",
categories_list_url: "/api/categories/"
};
this.getNewUrl = this.getNewUrl.bind(this);
this.activeorArchive = this.activeorArchive.bind(this);
};
Upvotes: 0
Views: 317
Reputation: 66
Try this approach:
activeorArchive = () => {
const newListURL = `/api/assessments/archived=${this.state.active ? 'false' : 'true'}`;
this.setState({assessments_list_url: newListURL});
};
And please let me know, if it worked for you :)
Upvotes: 2