Reputation: 359
Why doesn't updateCardContentsBuggy()
work?
If I use updateCardContentsBuggy()
, then render()
never uses the new values. Here are some logs. As you can see, title
never has the new values when I call it from render()
However, if I use updateCardContents()
, render()
uses the new values. The log shows that render()
gets the new state values.
Here is my code:
import React from 'react';
import './css/main.css';
import './css/w3.css';
import CardHTMLTemplate from './models/CardHTMLTemplate.js';
var axios = require('axios');
class CardClient extends React.Component {
constructor(props) {
super(props);
this.state = {
_id: null,
title: "",
description: "",
tags: "",
createdById: 0,
createdAt: "",
updatedAt: "",
urgency: 50,
isNew: false
}
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.updateCardContents = this.updateCardContents.bind(this);
this.updateCardContentsBuggy = this.updateContentsBuggy.bind(this);
}
updateCardContents(newCard) {
this.setState({
description: newCard["description"],
title: newCard["title"],
urgency: newCard["urgency"]
});
}
updateCardContentsBuggy(newCard) {
Object.keys(newCard).forEach(key => {
this.setState({
key: newCard[key]
}, function() {
console.log("Updated:" + key + " --> " + this.state.key + "\n");
});
});
}
componentDidMount() {
axios.get('/read-card', {
params: {
_id: null
}
})
.then((response) => {
var card = response["data"][0];
this.updateCardContents(card);
// this.updateCardContentsBuggy(card);
})
.catch(function (error) {
console.log(error);
});
}
handleInputChange(event) {
this.setState({
[event.target.name]: event.target.value
});
}
handleSubmit(event) {
event.preventDefault();
}
render() {
console.log("render() title = " + this.state.title);
return (
<CardHTMLTemplate
title={this.state.title}
description={this.state.description}
handleInputChange={this.handleInputChange}
urgency={this.state.urgency}
handleSubmit={this.handleSubmit}
/>
)
}
}
export default CardClient;
Upvotes: 0
Views: 36
Reputation: 4639
You are updating key
not [key]
in updateCardContentsBuggy
. I think you want:
updateCardContentsBuggy(newCard) {
Object.keys(newCard).forEach(key => {
this.setState({
[key]: newCard[key]
}, function() {
console.log("Updated:" + key + " --> " + this.state.key + "\n");
});
});
}
Upvotes: 3