Home > Back-end >  Getting data from mongoose on server but an empty array in React
Getting data from mongoose on server but an empty array in React

Time:03-06

When I try to return a data from moongoose using React it just display an empty array using a useEffect and it return the data when I change something inside the page , also when I try to map the data, it shows nothing :

server side:

const mongoose = require('mongoose');

const Partner = new mongoose.Schema({
    name: { type: String },
    website: { type: String },
},
    { collection: 'partner-data' }
);

const partnerModal = mongoose.model('partner-data', Partner);

module.exports = partnerModal;


app.get('/getpar', (req, res) => {
    Partner.find().then(result => res.send(result)).catch(err => console.log(err))
})

client side :

const [par, setPar] = useState([]);

    useEffect(() => {
        
        async function getPartners() {
            const req = await axios.get("http://localhost:1200/getpar");
            setPar(req.data);
            console.log(par);
        }

        getPartners();
    },[])

{par.map(p => {p.name})}

The server side is working fine, it displays the data when I recall it but when I console log inside the client side it shows an empty array and it doesn't display any data.

CodePudding user response:

You are "consol logging" before React has updated the state, to be sure that you are getting the data, do this in getPartners:

console.log(req.data);

And outside your useEffect somewhere, do:

console.log(par);
  • Related