1

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.

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

oh i didn't know that , thank you its working

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.