I am a beginner in react and I am trying to fetch data from my database using axios request . I have assigned res.data to my state but when I am trying to print , it is empty. I tried to send alert message by printing blogs, but it is empty. When I passed JSON.stringify(res.data) in alert , It returned correct collections of my database.
const express = require('express');
const app = express();
const cors = require("cors");
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const blog = require('./model/blog');
const routes = express.Router();
app.use(cors());
app.use(bodyParser.json());
mongoose.connect("mongodb://127.0.0.1:27017/dummies");
const con = mongoose.connection;
con.on('open',(err,res)=>{
console.log("Connected to the database");
});
routes.route('/').get((req,res)=>{
blog.find((err,blog)=>{
res.json(blog);
})
});
routes.route('/add').post((req,res)=>{
let b = new blog(req.body);
b.save().then((err)=>{
res.send("Saved");
});
});
app.use('/',routes);
app.listen(3000,()=>{
console.log("Connected on port 3000");
})
Above is server.js file.
import React , {Component} from 'react';
import {Link} from 'react-router';
import Search from '../Search/Search';
import './Home.css';
import axios from 'axios';
const SingleBlog = (props)=>{
return(
<div>
<p>{props.topic}</p>
</div>
)
}
class Home extends Component{
constructor(props){
super(props);
this.state = {
blogs:[]
}
}
componentDidMount(){
axios.get("http://localhost:3000/").then(res=>{
this.setState=({
blogs:res.data
});
})
alert(this.state.blogs);
}
componentDidUpdate(){
axios.get("http://localhost:3000/").then(res=>{
this.setState=({
blogs:res.data
})
})
}
render(){
return(
<div>
<div className="banner">
<Search/>
</div>
{this.state.blogs.map(blog=>{
return(
<div>
<p>{blog.topic}</p>
</div>
)
})}
</div>
);
}
}
export default Home;
This is my component where I am trying to display the fetched values
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const Blog = new Schema({
topic:{
type:String
},
desc:{
type:String
}
});
module.exports = mongoose.model("Blog",Blog);
This is my database model.