简体   繁体   中英

Getting data from mongoose on server but an empty array in React

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.

You are "console logging" before React has updated the state . In fact updating a state is an asynchronous task. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM