0

I'm working on something that uses onChange saving (like auto saving on Gmail or docs on Google Docs) and I would like to save text from on onChange. I can do it with just displaying text from the input on onChange and then printing it in the component, but when the database is used the whole thing clogs. There are significant lags, it sometimes misses some letters and generally the faster you type the worst data is being logged to the database.

This is my input tag:

<input
 value={data.name}
 onChange={(e) => updateUserData({name: e.target.value})}
/>

This is my useEffect:

useEffect(() => {
    checkIfExists().then((exists)=>{
      if(!exists)
      {
        createUserData().then(()=>{
          getUserData().then((data)=>{
            setData(data)
          })
        })
      }
      else
      {
        getUserData().then((data)=>{
          setData(data)
        })
      }
    })
  }, [data])

Is my approach wrong? What should I change in order for this to work as expected?

Thanks a lot in advance

IVOBOT
  • 61
  • 8

1 Answers1

0

It wasn't that hard. My code was making a lot of requests, so the saves should be for example grouped and saved later.

lodash might be helpful for debounce

My fixed code:

const debouncedSave: DebouncedFunc<(data: userDataType) => Promise<void>> = useCallback(
    debounce(async (data: userDataType) => {
      
      await updateUserData(data);
      setSavingState("done");
      
    }, 1500), []);

  const [savingState, setSavingState] = useState("done");

  useEffect(() => {
    setSavingState("saving");
    if (data) {
      debouncedSave(data);
    }
  }, [data, debouncedSave])

  useEffect(() => {
    checkIfExists().then((exists)=>{
      if(!exists)
      {
        createUserData().then(()=>{
          getUserData().then((data)=>{
            setData(data)
          })
        })
      }
      else
      {
        getUserData().then((data)=>{
          setData(data)
        })
      }
    })
  }, [])

Useful resources: 1. 2.

IVOBOT
  • 61
  • 8