Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

121
Visualizações
How to get id of an object from firebase

I am trying to get id of an object after set that object. But I am getting type error. TypeError: Cannot read properties of undefined (reading 'val'). How should I do that with firebase 9?

Here is the code that I want to work:

set(push(ref(db, "expenses")), expense)
      .then((snapshot) => {
        console.log(snapshot.val());
        dispatch(
          addExpense({
            id: snapshot.key,
            ...expense,
          })
        );
      })
      .catch((e) => {
        console.log("This failed.", e);
      });

Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Why your code doesn't work

The documentation of set(ref, value) shows that is is defined as:

function set(ref: DatabaseReference, value: unknown): Promise<void>

It returns a Promise<void>, so there's no snapshot being passed to your then.

If the promise resolves (and thus your then callback gets called) that the expense was written to the database on the server as is.


How to fix it

If you want to get the key of the push call, you can capture that outside of the set call already:

const newRef = push(ref(db, "expenses"));
set(newRef, expense)
  .then(() => {
    dispatch(
      addExpense({
        id: newRef.key,
        ...expense,
      })
    );
  })
  .catch((e) => {
    console.log("This failed.", e);
  });

Calling push is a pure client-side operation, which is synchronous, so that doesn't require await or then (which should be used with asynchronous operations).


Further considerations

Note though that now you're only showing the expense locally after it's been written to the server. If that is a requirement for your use-case, then 👍. But when using Firebase it is quite common to:

  1. Use a permanent, onValue listener on expenses to show the latest expenses in the UI.
  2. Write the new expense with a simple call, without a then() listener: set(push(ref(db, "expenses")), expense);
  3. The Firebase SDK will then immediately call the local onValue listener with the new value, with the assumption that the write will succeed.
  4. So your UI will show the local value straight away, giving the user an almost instant response.
  5. In the (more uncommon) case that the server (i.e. your security rules) rejects the write operation, the SDK calls onValue again with the corrected data, so your UI can update the state.
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda