javascriptreactjsautosave

Passing `id` to `useCallback` when using `react-autosave`?


In the README of react-autosave, it's mentioned I should use useCallback but I'm not sure how to pass id to it as I need that in the mutation.

id & text is everchanging in my case.

const updateDraft = useCallback(
    (newText: string) => {
      console.log('updateDraft')
      console.log({ id: snap.doc.id, text: newText })
      updateDocs({ id: snap.doc.id, text: newText })
      toggleIsSaved(true)
    },
    [snap.doc.id]
  )

  useAutosave({
    data: snap.doc.text,
    onSave: updateDraft,
  })

I am using valtio as a global state manager. That's where the snap.doc.id is coming from. But everytime, the 1st snap.doc.id gets passed because of useCallback as the same function is used so every time it mutates the same row as snap.doc.id remains the same.

Complete reproduction on branch react-autosavehttps://github.com/deadcoder0904/docs-autosync/tree/react-autosave


Solution

  • I passed the complete doc to it & destructured it in useCallback like:

    const updateDraft = useCallback(
        ({ id, text }: Doc) => {
          if (id !== '') {
            updateDocs({ id, text })
          }
          toggleIsSaved(true)
        },
        [snap.doc.id]
      )
    
      useAutosave({
        data: snap.doc,
        onSave: updateDraft,
      })
    

    Turns out, this works perfectly fine.