Home > Net >  Is it possible to know if a setState was called at least once?
Is it possible to know if a setState was called at least once?

Time:11-08

I have a form I am updating some fields with, but I would not like to send the updated fields unless they have been updated. I am controlling the form state for the inputs with some useState like so:

const [description, setDescription] = useState(
  data?.description ?? '',
);

When the user clicks the submission button, I want to send only the form inputs that were updated - so I am wondering if it is possible to know if the setState function was called at all. So it would be something like :

 let submission = {};
  if(*setDescription was called*) {
  submission.description = description
}
 commit(submission);

I was originally thinking of just doing :

 let submission = {};
  if(description !== data?.description) {
  submission.description = description
}
 commit(submission);

but the data gets mutated a bit on certain inputs, so it's a pain to pull out the values and compared them. Is something like this possible? Thanks!

CodePudding user response:

Using a custom hook with a flag should do the trick:

import { useState } from 'react';

export function useTrackedState(initialState) {
  const [state, setState] = useState(initialState)

  const setTrackedState = (...args) => {
    setTrackedState.wasSet = true
    return setState(...args)
  }

  setTrackedState.wasSet = false

  return [state, setTrackedState]
}

From your example:

const [description, setDescription] = useTrackedState(
  data?.description ?? '',
);

// ...

let submission = {};
if (setDescription.wasSet) {
  submission.description = description
}
commit(submission);
  • Related