Reputation: 775
I'm making a to-do list in React. The items are stored in an object in the app's state. When the user checks the box, I can update the state, but not display the updated state. I know that changes to the state do not always immediately update the component, so I've tried passing the render()
function as a callback to the setState()
function, but I get an error saying Invalid argument passed as callback. Expected a function. Instead received: [object Object]
. I've also tried adding the componentDidUpdate()
function but didn't have any success using that method because I don't understand how it's triggered. How can I update the state then immediately display the updated state on the page?
So far what I have it this function which is triggered when a checkbox is checked/unchecked.
constructor(props) {
super(props);
this.state = {
isLoading: null,
isDeleting: null,
list: null,
title: "",
term: "",
content: []
};
}
async componentDidMount() {
try {
const list = await this.getList();
const { title, content } = list;
this.setState({
list,
title,
content
});
} catch (e) {
alert(e);
}
}
checkedChange = async event => {
let todos = Object.assign({}, this.state.content);
let key = event.target.attributes[0].value;
if(event.target.checked) {
todos[key] = true;
this.setState({todos});
}
else {
todos[key] = false;
this.setState({todos});
}
};
Upvotes: 0
Views: 55
Reputation: 11591
The syntax this.setState({todos})
is shorthand equivalent to writing this.setState({todos: todos})
. So you are not updating this.state.content
which I suspect is what you want to be doing. So try this.setState({content: todos})
.
Edit: I highly recommend you install and use the Chrome React developer tools. It will show up in your dev tray as a tab next to Console, Inspector, etc. It is extremely useful for debugging and visualizing what's going on in your components.
Upvotes: 2