How to Insert Multiple Items using React-Native-sqlite-Storage

Asked

Viewed 58 times

-1

I was developing an application using the React-Native-sqlite-Storage but I came across a very strange problem, time my code works and time does not, I can not understand, to try to investigate I came to the following code:

/* Conexão */
const db = SQLite.openDatabase(
  'candy.db',
  '1.0',
  'candy',
  20000,
  () => console.log('banco de dados aberto'),
  (error) => console.log('error', error),
);

/* Objeto estático para teste */
const order = {
  items: [{
      nome: "Snickers",
      quantidade: 1,
      preco: 3,
      codigo_de_barras: 123
    },
    {
      nome: "Bala de goma",
      quantidade: 1,
      preco: 1,
      codigo_de_barras: 1234
    },
  ],
  cliente: {
    id: 1
  },
  status: "NAO PROCESSADO"
};

/* Transação */
db.transaction(tx => {
  tx.executeSql(
    "INSERT INTO pedidos (id_usuario,status) VALUES (?,?)", [order.cliente.id, order.status],
    () => {},
    (e) => console.log(e)
  )

  /* Parte que ocorre o erro */
  order.items.forEach(produto => {
    db.executeSql(
      `INSERT INTO pedido_itens (id_pedido,codigo_de_barras,quantidade, preco) 
          VALUES((SELECT last_insert_rowid()+1 from pedidos), ?,?,?)`, [produto.codigo_de_barras, produto.quantidade, produto.preco],
      () => console.log(produto, "inserido com sucesso no banco de dados"),
      (e) => console.log(e)
    )
  })
})

The strange thing is that I have two items in order.items both items are displayed on the console but are not always entered in the database, this part does not make sense to me because then going through the same function together. If it were still the case that they will be inserted as different times would make sense to me because this library offers support for precedents that I am not using at the moment, but even this strange behavior I was able to develop normal. Can someone give me a direction of what to do?? I no longer have ideas.

1 answer

-1


I suggest you use an asynchronous function for this. Even if it doesn’t make sense from the outside, but this matter of calling if you run over is real.

class DataAccess {
    executeSql = async(sql, params) => {
            const tx = await this.transaction();
            tx.executeSql(sql, params, () => Promise.resolve(), error => {
                throw error;
            });
        }
 /* outras implementações */
}
const da = new DataAccess();

Then loop the items by calling the asynchronous function we created.

async function insert() {
    // promise all não garante a ordem execução 
    // entao usamos o await (async)
    await Promise.all(order.items.map(async produto => {
        try {
            await da.executeSql(`INSERT INTO pedido_itens (id_pedido,codigo_de_barras,quantidade, preco) 
      VALUES((SELECT last_insert_rowid()+1 from pedidos), ?,?,?)`, [produto.codigo_de_barras, produto.quantidade, produto.preco]);
        } catch (error) {
            console.log(error.message);
        }
    }));
}

I hope I’ve helped.

  • 1

    I discovered the problem was in this SQL : INSERT INTO pedido_itens (id_pedido,codigo_de_barras,quantidade, preco) VALUES((SELECT last_insert_rowid()+1 from pedidos), I switched to : INSERT INTO pedido_itens (id_pedido,codigo_de_barras,quantidade,preco) VALUES ((SELECT id FROM pedidos ORDER BY id DESC LIMIT 1),?,?,?) and everything worked, I will choose your question and as soon as you free up the time of Bounty I make you beautiful, it was well worth it were not your answer and I do not know if I would ever touch this project again.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.