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

116
Visualizações
How can I save multiple messages and save it in separate fields in firestore?

This is the firestore document of a certain user:

enter image description here

This is how I'll save messages to be saved in firestore:

  const [msg, setMsg] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    try {
      const userRef = firestore.collection("users").doc(uid);
      const ref = userRef.set(
        {
          msg,
        },
        { merge: true }
      );
      console.log(" saved");
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <div>
        <form onSubmit={handleSubmit}>
          <TextField
            value={msg}
            onChange={(e) => setMsg(e.target.value)}
          />
          <Button type="submit">
            Submit
          </Button>
        </form>
    </div>
  );
};

In this way, I can save the message in the firestore, however, if I'll send another one, it will replace the previous message saved in it. How can I save a message in firestore and save another message without it affecting the previous message?

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

0

I understand that you are overriding the same document in the users collection. This is probably (we don't see the entire code) because you don't change the value of uid between the two writes. uid being the Document ID, it is overwritten (even if you use the { merge: true } option, if the msg object contains existing fields, they are overwritten).

You mention that you save messages, so I guess you want to save several messages for a given user (this user being identified by uid). So you could have a subcollection under the user's document and let Firestore generates a new Document ID each time you add a document to this collection, by using the add() method.

Something along the following lines:

const messagesCollection = firestore.collection("users").doc(uid).collection('messages');

const messagePayload = {foo: 'bar', bar: 'foo'};
messagesCollection.add({messagePayload});
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