I'm creating a website using MERN and I am struggling to pass the username in my URL to React.
I want to get every blog posts from one user that I pass in the URL. For this, I use find() in my server.js.
This works on my NodeJS server http://localhost:3333/
app.get('/blog/:username', (request, reponse) => {
mongo.connect(url, function (err, db) {
var dbo = db.db("mern-pool");
var cherche_user = request.params.username;
dbo.collection("posts").find({username: cherche_user}).toArray(function(err, result) {
if (err) throw err;
console.log(result);
var students = result;
reponse.send(result);
db.close();
});
});
});
I need to pass that data into my React blog-indiv component.
However this doesn't work, my console.log(this.state) render an empty Array.
It does work when I change axios.get('http://localhost:3333/blog/:username') to axios.get('http://localhost:3333/blog/user123')
export default class BlogIndiv extends Component {
constructor() {
super();
this.state = {
posts: []
};
}
componentDidMount() {
axios.get('http://localhost:3333/blog/:username')
.then(response => {
this.setState({ posts: response.data });
console.log(this.state);
})
}
render() {
return(
<div>
<h1>HE</h1>
{this.state.posts.map(e => {
return (
<Sub title={e.title}
content={e.content}
author={e.username}
/>
)}
)}
</div>
)
}
}