1

I'm using firebase's realtime database with react to create a CRUD, but the update function is making me very confused for two reasons.

1 - What is the most correct method to be used to do a simple update of one or more attributes? Sometimes I see using update(), other times updateDoc() other times I see set(). As a beginner in firebase (1st application I'm trying to do) I feel lost and confused with so many things, not to mention the difference between realtime and firestore that I can't quite understand why there are two databases inside one (!!?? )

2 - I'm trying to do the crud and as I said I'm not getting it to work. It's not giving any error on the console and I still get the success message, but the data doesn't update either on the screen or in the database, I can't understand which part I'm wrong. Something's missing? The code is:

useTransaction.tsx

  async function updateTransaction(transaction: Transaction) {
    await update(ref(realTimeDatabase, `transactions/${transaction.id}`), {
      transactionUpdate
    }).then(() => {
      const updatedTransaction = transactions.map((transaction) => {
        return transaction.id === transactionUpdate?.id ? transactionUpdate : transaction
      });
  
      setTransactions(updatedTransaction)
      toast.success('Atualizada com sucesso')
      console.log('Atualizada no firebase');

    }).catch((err) => {
      toast.error('Ocorreu um erro ao atualizar')
      console.log(err);
    })
  }

UpdateTransactionModal.tsx

  async function handleUpdateTransaction(event: FormEvent) {
    event.preventDefault();
    await updateTransaction({
      id,
      title,
      amount,
      category,
      type,
      createdAt: String(new Date()),
    })    
    onRequestClose()
  }

The repo is: https://github.com/eltonsantos/eurorcamento

UPDATE:

console.log("ID1: " + transactionUpdate?.id) >> undefined
console.log("ID2: " + transaction.id) >> -NJCBBEMVRMymMw-1tjI
Elton Santos
  • 571
  • 6
  • 32
  • 1
    `updateDoc` is an API for Firestore, not the Realtime Database. For the distinction between the two, see https://stackoverflow.com/questions/46549766/whats-the-difference-between-cloud-firestore-and-the-firebase-realtime-database. I recommend removing this part of your question, as your #1 essentially makes it a duplicate of that question. – Frank van Puffelen Dec 14 '22 at 04:32
  • 1
    To help debug the problem in the code, please: 1) add `console.log` of `transaction.id` and `transactionUpdate` to your code, 2) edit your question to include the updated code and its output. – Frank van Puffelen Dec 14 '22 at 04:33
  • 1
    @FrankvanPuffelen done. I've identified the problem, but I don't know how to get to the solution – Elton Santos Dec 14 '22 at 04:39
  • 1
    With the information provided right now, the best I can say is that your `id` in `handleUpdateTransaction` is `undefined`. I recommend setting a breakpoint on the code that calls that function, and check what `id` is there, and work your way upwards from there until you find where you expect `id` to get its value and that's not happening. – Frank van Puffelen Dec 14 '22 at 04:45

1 Answers1

0

I managed to solve it and I'll share the answer here:

my transactionUpdate state is unnecessary and confusing here, because the new transaction is already received with the name transaction in the updateTransaction function and a state is not needed to retrieve the value of the transaction that is being updated.

So to fix the problem, I just changed the .map() a little to stop using the transactionUpdate variable and use the transaction that was received by parameter.

So I fixed it because there were two variables with the name transaction, so I changed the one in the map to "t" to be different. And it worked!

Code is here:

  async function updateTransaction(transaction: Transaction) {
    await update(ref(realTimeDatabase, `transactions/${transaction.id}`), {
      title: transaction.title,
      amount: transaction.amount,
      type: transaction.type,
      category: transaction.category
    }).then(() => {
      setTransactions(transactions.map((t) => t.id === transaction.id ? transaction : t ))
      toast.success('Atualizada com sucesso')
      console.log('Atualizada no firebase');

    }).catch((err) => {
      toast.error('Ocorreu um erro ao atualizar')
      console.log(err);
    })
  }
Elton Santos
  • 571
  • 6
  • 32