Malaury Boudon
Malaury Boudon

Reputation: 732

How can I get the right response promise?

I'm trying to call my database and then put the datas inside a state. I tried many different way and I always got this type of response:

Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}

This is my function called:

function getEspaces() {
    return new Promise((resolve) => {
        db.transaction(tx => {
            tx.executeSql(
                `SELECT * FROM Espace`, [], (tx, results) => {
                    let espaces: Espace[] = [];
                    for (let cpt = 0; cpt < results.rows.length; cpt++) {
                        const item = results.rows.item(cpt)
                        const espace: Espace = {
                            name: item.name,
                            id_espace: item.id_espace
                        }
                        espaces.push(espace);
                    }
                    console.log("Get espaces");
                    resolve(espaces);
                });
        });
    });
}

This is where I called it from another component:

const [espaces] = useState(getEspaces());

How can I fix it ? I can't put await inside a setState.

Thanks in advance

Upvotes: 1

Views: 45

Answers (1)

Steve Holgado
Steve Holgado

Reputation: 12071

You can initially set the espaces state to an empty array and then use a useEffect hook to fetch the data and set the state when it resolves:

const [espaces, setEspaces] = useState([])

useEffect(() => {
  getEspaces().then(data => setEspaces(data))
}, [])

I hope this helps.

Upvotes: 3

Related Questions