简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM