0

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.

Kunal Rai
  • 340
  • 2
  • 6
  • 15
  • Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) Also, `setState` is async. – jmargolisvt May 14 '19 at 17:13

1 Answers1

3

The problem at first glance looks like your are assigning instead of calling setState.

This code

this.setState=({
  blogs:res.data
})

should be in this way (notice that I removed the =)

this.setState({
  blogs:res.data
})
danpeis
  • 166
  • 6
  • Thanks. It solved the issue but the alert in componentDidMount() still returns empty. Can you please explain that – Kunal Rai May 14 '19 at 17:37
  • This is because, `setState` is asynchronous and it does not reflect the state immediately. Change the alert code to `alert(res.data)`. – danpeis May 14 '19 at 17:43