Reputation: 1
The user.entries state gets updated; however, it's not getting passed immediately to the child component, it only gets updated on the second button submit and it passes the first user.entries not the second one, though.
App.js file:
class App extends Component {
constructor(){
super();
this.state = {
input: '',
imageUrl:'',
box:{},
route:'signin',
isSignedIn: false,
user: {
id: '',
name: '',
email: '',
entries: 0,
joined: ''
}
}
}
onButtonSubmit = () => {
this.setState({imageUrl: this.state.input})
app.models.predict(Clarifai.FACE_DETECT_MODEL,this.state.input).then(response => {
if (response){
fetch('http://localhost:3000/image', {
method: 'put',
headers: {'content-type': 'application/json'},
body: JSON.stringify(
{id: this.state.user.id}
)
})
.then(resp => resp.json())
.then(count => {Object.assign(this.state.user, {entries: count})});
}
this.displayFaceBox(this.calculateFaceLocation(response))
}).catch(err => console.log(err));
}
render(){
return(
<div>
<Rank name={this.state.user.name} entries={this.state.user.entries} />
</div>
)
};
Rank.js file:
import React from 'react';
const Rank = ({name, entries}) => {
return(
<div className='mv2'>
<p className='f3 mv0 white'>
{`Welcome back ${name}, your entries count is...`}
</p>
<p className='f1 mv0 b white'>
{`#${entries}`}
</p>
</div>
)
}
export default Rank;
Upvotes: 0
Views: 23
Reputation: 5388
It is not re-rendering the component after you update since you are directly updating the object. You need to instead use this.setState
fetch(...)
.then(...)
.then(count => {
this.setState((previousState) => ({
user: {
...previousState.user,
entries: count,
}
}));
});
Along with updating the state, this.setState
also triggers a re-render of the component which is required to see the updated state on the UI as soon as the state is updated.
Upvotes: 2