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

251
Vistas
CRUD in React with Firestore for data in an array

It's my first time using Firebase as my backend and I can successfully access and fetch the data in my React App, but I have problem with CRUD operations.

Example of my collection:

- closets (collection)
        - unique ID (specific user) 
                   - name (string)
                   - shorts (array of objects - map)
                           - 0 (first object in array)
                              - name (string)
                              - image (string)
.........
.........

I can read all the files, but I can't update or delete them. I need to access all data in arrays (e.g shorts array based on example above) and be able to change name or remove the whole object.

Using custom hook to map the data:

export const useGetData = () => {
  const [documents, setDocuments] = React.useState([]);
  const db = firebase.firestore();
  React.useEffect(() => {
    db.collection("closets")
      .get()
      .then((querySnapshot) => {
        let arr = [];
        querySnapshot.docs.map((doc) =>
          arr.push({ id: doc.id, name: doc.data() })
        );
        setDocuments(arr);
      });
  }, [db]);
  return [documents];
};

Here I am trying to update name in dress array

const [nameValue, setNameValue] = React.useState("");

  const db = firebase.firestore();
  const getNameValue = (event) => {
    setNameValue(event.target.value);
  };

  const updateValue = () => {
    db.collection("closets")
      .doc(doc)
      .update({
        "dress.name": nameValue
      })
      .then(function () {
        console.log("Document successfully updated!");
      })
      .catch(function (error) {
        console.error("Error updating document: ", error);
      });
  };

  return (
    <>
      <input onBlur={getNameValue} type="text" />
      <button onClick={updateValue}>Update</button>
    </>

Getting error s.indexOf is not a function

I am not really sure how achieve updating this specific string in object, which is part of array.

Here is created example in codesandbox, for better understanding:

https://codesandbox.io/s/second-leeway-test-forked-ii0p6

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can update the array using:

firebase.firestore.FieldValue.arrayUnion(elem)
firebase.firestore.FieldValue.arrayRemove(elem)

See: https://firebase.google.com/docs/firestore/manage-data/add-data#update_elements_in_an_array

To update an element you must first remove it from the array and then add the modified one.

However, I suggest you model the database through subcollections, so as to simplify their management, like this:

- closets (collection)
    - unique ID (doc) 
               - name (string)
               - shorts (collection)
                       - short (doc)
                          - name (string)
                          - image (string)

See: https://firebase.google.com/docs/firestore/data-model#subcollections

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