Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

117
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda