0

I am working on React native. I am getting data to and from the server. That data doesn't have key isFavorite, so I want to add isFavorite=true (or false) to all items.

If the item is present in sqlite, I want to set isFavorite = true (OR false) if the item is preset in Sqlite DB Table. I just want to set the isFavorite key for items in the array and set this array to the state domains.

The code below executes fine, but it executes after this.setState({ domains: arr })1 and isFavorite` is not applied to the state domains.

    setFavorites() {
        let arr = this.state.domains.map((item, index) => {        
            db.transaction((tx) => {
                try {
                    tx.executeSql(
                        'SELECT * FROM table_favorites WHERE id=' + item.product_id, [],

                        (tx, results) => {
                            var len = results.rows.length;

                            if (len > 0) {
                                item.isFavorite = true
                                console.log("YES:", item.product_id)
                            } else {
                                item.isFavorite = 
                                console.log("NO:", item.product_id)
                            }
                        }
                    );
                    
                } catch (error) {
                }
            });
            return { ...item }
        })

        this.setState({ domains: arr })
            console.log("ARRA:", arr);

    }
   
ebbishop
  • 1,833
  • 2
  • 20
  • 45
Jagdish Suryawanshi
  • 359
  • 1
  • 4
  • 13
  • As db.transaction is async function, you should use await or db's promise function so that your map function waits until db transaction is finished. – robdev91 Dec 02 '20 at 10:02
  • `return { ...item }` returns a copy of the original item because db functions are async. You need to wait for all queries to finish, either using `Promise.all` or a for loop and async/await. Further reading: https://meta.stackoverflow.com/questions/254895/general-javascript-asynchronicity-reference-for-close-voting –  Dec 02 '20 at 10:08
  • Duplicate: [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) –  Dec 02 '20 at 10:09
  • i Used Promise also but it executes state first – Jagdish Suryawanshi Dec 02 '20 at 10:23

0 Answers0