Reputation: 65
I'm working on a self project React for front-end and node for back-end, part of the app is that when a user submits an image url it counts the entries and it updates in the server then it should re-render on the front-end to the screen. The problem is it doesn't re-render, i have console.log tested and everything works from the server side, the problem is in the setState in react wont re-render and i'm hoping any one help me understand why it is not working?
Here is the code related to my problem
class App extends Component {
constructor() {
super()
this.state = {
input: '',
imgUrl: '',
box: {},
route: 'signin',
isSignedIn: false,
user: {
id: '',
name: '',
email: '',
entries: 0,
joined: '',
},
}
}
loadUser = data => {
this.setState({
user: {
id: data.id,
name: data.name,
email: data.email,
entries: data.entries,
joined: data.joined,
},
})
}
onButtonSubmit = () => {
fetch('http://localhost:3001/image', {
method: 'put',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
id: this.state.user.id,
}),
})
.then(response => response.json)
.then(count => {
this.setState({ ...this.state.user, entries: count })
})
.catch(err => console.log(err))
}
}
render() {
return (
<div className="App">
<Navigation
isSignedIn={this.state.isSignedIn}
onRouteChange={this.onRouteChange}
/>
{this.state.route === 'home' ? (
<div>
<Rank
name={this.state.user.name}
entries={this.state.user.entries}
/>
<ImageLinkForm
onInputChange={this.onInputChange}
onButtonSubmit={this.onButtonSubmit}
/>
<FaceRecognition box={this.state.box} imgUrl={this.state.imgUrl} />
</div>
) : this.state.route === 'signin' ? (
<Signin loadUser={this.loadUser} onRouteChange={this.onRouteChange} />
) : (
<Register
loadUser={this.loadUser}
onRouteChange={this.onRouteChange}
/>
)}
</div>
)
}
this code is suppose to print the entries count on the screen but its not
this.setState({...this.state.user, entries: count})
here is the server side where entries gets updated and sent to the front-end
app.put('/image', (req, res) => {
const { id } = req.body
let found = false
database.users.forEach(user => {
if (user.id === id) {
found = true
user.entries++
return res.json(user.entries)
}
})
if (!found) {
res.status(400).json('not found')
}
})
here is the rank Component where entries gets printed
import React from 'react';
const Rank = ({ name, entries}) => {
return (
<div>
<div className='rank'>
{`${name} your current rank is...`}
</div>
<div className='white f1 '>
{entries}
</div>
</div>
);
}
export default Rank;
Thanks in advance.
Upvotes: 0
Views: 152
Reputation: 33984
I don’t see any use of doing ...this.state.user in setState So
Change
this.setState({...this.state.user, entries: count})
To
this.setState({entries: count})
Upvotes: 1