Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

typeError _ref is undefined

I jump into react with just the basic about javascript, I'm making a query in my server that handle mysql and the connection is fine but the return is where I have a problem,it suppose to return a JSON with the query but I found error typeError _ref is undefined here is the function where I connect to my API

callDB(){
    fetch('http://localhost:4000/lista')
    .then((response)=>{
        response.json()
    })
    .then(({data})=>{
        console.log(data);
    })
    .catch((err)=>{console.log(err);});
}

In the data part is where it doesn't work any ideas?thanks before anything

like image 589
Antonio Gonzalez Avatar asked Apr 28 '26 02:04

Antonio Gonzalez


2 Answers

It happens when trying to destructure an object from the undefined value, in your case it's { data }.

So in this particular case returning response.json() from the previous then() handler helps, but other readers may have this problem in other cases as well, in this case you either need to provide a default value like {} or explicitly check for undefined before trying to desctucture

like image 97
adlerer Avatar answered Apr 30 '26 15:04

adlerer


You need to return response.json() in your Promise handler :

callDB(){
    fetch('http://localhost:4000/lista')
    .then((response)=>{
        return response.json()
    })
    .then(({data})=>{
        console.log(data);
    })
    .catch((err)=>{console.log(err);});
}
like image 39
Hamza El Aoutar Avatar answered Apr 30 '26 15:04

Hamza El Aoutar