react-firebase-hooks icon indicating copy to clipboard operation
react-firebase-hooks copied to clipboard

Support for mutating data with hooks

Open kdawgwilk opened this issue 6 years ago • 4 comments

I would like to see some mutation support for making changes in firebase not just reading data. I would look to apollo mutation hooks for inspiration. Ideas that I have in mind are along these lines:

function useDocumentUpdate<T>(docRef: firestore.DocumentReference): [(data: T) => void, boolean, Error | undefined] {
  const [mutating, setMutating] = useState(false)
  const [error, setError] = useState<Error  | undefined>(undefined)

  const updateDoc = (data: T) => {
    setMutating(true)
    docRef.update(data).catch(e => setError(e)).finally(() => setMutating(false))
  }

  return [updateDoc, mutating, error]
}

kdawgwilk avatar Sep 05 '19 04:09 kdawgwilk

@kdawgwilk this is an interesting idea, although I'm not sure what the real benefit is over just calling update on the underlying DocumentReference directly?

chrisbianca avatar Sep 14 '19 11:09 chrisbianca

I could see the use case here because the hook handles loading and error state for you, which is much harder to handle by hand!

Though the loading state is a bit tricky because I believe Firebase uses optimistic logic to fake an "instantaneous" mutation, doesn’t it?

thib92 avatar Sep 18 '19 13:09 thib92

Thanks for taking the time to write these hooks! I was just going to open an issue for this... I've never just partied on the actual doc that gets returned -- that's pretty strong coupling the the DB component, and even ignoring hygiene, the UI usually needs a model that's a bit different than the doc. Being able to go from doc-to-model on the way out and model-to-doc on the way in would be cool -- just need to pass an optional fn to the hook. (Though I guess not necessary for this wrapper as it doesn't write.)

thelazydogsback avatar Dec 27 '19 22:12 thelazydogsback

Any updates?

isrmicha avatar Apr 04 '22 12:04 isrmicha