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

250
Visualizações
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 Respostas
Responde à pergunta

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 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