I'm making a Todolist. The Submit component to handle input from user and make PUT request to the server to update the database. The Progress component shows the progress. When user submits, Submit will send props to Progress and Progress will call axios.get to get data and update the state. The props is passed successfully and the Progress state's variables do change but the component is not re-rendered.
submit.js
import Progress from './progress';
export default class Submit extends Component {
constructor(props) {
super(props);
this.state = {
updateProgress: 'No'
}
}
handleSubmit = (e) => {
// ...
this.setState({updateProgress: 'Yes'}));
}
render() {
return (
<div>
<div style={{visibility: 'hidden'}}>
<Progress update={this.state.updateProgress} />
</div>
// Form
</div>
)
}
}
progress.js
export default class Progress extends Component {
constructor(props) {
super(props);
this.state = {
tasksDone: 0
};
}
getData = () => {
axios.get('/task')
.then(res => {
let resData = res.data[0];
this.setState({tasksDone: resData.done});
})
.catch(err => console.log(err));
}
componentDidUpdate(prevProps) {
if (this.props.update != prevProps.update) {
console.log('Props changed');
this.getData();
}
}
componentDidMount() {
this.getData();
}
render() {
return (<div>You have done: {this.state.tasksDone}</div>)
}
}
I know getData() won't be called again after the first submit because the props passed doesn't change but that's not the case because it doesn't work the first submit already. When I use console.log(this.state.tasksDone) in componentDidUpdate() the tasksDone is updated but the div is not re-rendered, even I tried using forceUpdate() after calling getData(). I have read other questions and they said mutating state doesn't trigger re-render. Is my setState just mutating? I see changing state this way is very common. What am I missing?
Reproduce problem: https://codesandbox.io/s/determined-curie-ipr6v
The problem lies in your use for Progress. The Progress you are updating is not the Progress that is shown on the display.
https://codesandbox.io/s/vigilant-ardinghelli-vd9nl this is the working code you provided.