Reputation: 1896
I am trying to do a simple task, with an input box in which text is entered and on submit gets listed below. I am unaware of how to reflect changes without refresh.
App.js
constructor(props){
super(props);
this.state={
todoList:[]
}
}
componentWillMount(){
console.log("mounting app");
axios.get('http://localhost:8888/todoitems').then((res)=>{
this.setState({todoList: res.data});
});
}
save=()=>{
var data={
name:this.refs.newvalue.value,
status:'started'
};
axios.post('http://localhost:8888/todoitem',data).then((res)=>{
console.log("data inserted is":data);
});
}
render() {
return (
<div className="App">
<input type="text" ref="newvalue"/>
<button onClick={this.save}>Submit</button>
<table>
<tbody>
{
this.state.todoList.map(todo => (
<TodoList
key={todo.id}
id={todo.id}
name={todo.name}
status={todo.status}
click={this.update.bind(this,todo.id)}
/>
)})
}
</tbody>
</table>
}
TodoList.js
render() {
return (
<tr onClick={this.props.click}>
<td>{this.props.id}</td>
<td>{this.props.name}</td>
<td>{this.props.status}</td>
</tr>
);
}
By this, changes would be reflected only in refresh. But i need changes reflected instant. I tried with shouldcomponentupdate and componentwillupdate but i see nextProps as undefined.And i am naive on knowing how to proceed. Please favour.
Upvotes: 1
Views: 13660
Reputation: 16472
If you are returning the data after saving them, then you can simply reflect the changes without refreshing by adding that returned data to state like this
save=()=>{
var data={
name:this.refs.newvalue.value,
status:'started'
}
axios.post('http://localhost:8888/todoitem',data).then((res)=>{
console.log("data inserted is":data);
// When data is returned after successfull save
// add that data to the "todoList" state.
let todoList = [...this.state.todoList]
todoList.push(data)
// setting back the state will trigger a rerender and will show the changes on screen
this.setState({todoList})
})
}
Upvotes: 3
Reputation: 2704
You want this bit of code to render a Todo
component not a TodoList
:
{
this.state.todoList.map(todo=>{
return (
<Todo key={todo.id} id={todo.id} name={todo.name} status={todo.status} click={this.update.bind(this,todo.id)}/>
)
});
Or just pass the array into TodoList
and create Todo
in there.
Upvotes: 0