Skip to content

Instantly share code, notes, and snippets.

@vinibgoulart
Created February 24, 2023 17:34
Show Gist options
  • Save vinibgoulart/845aefd6cd5c086417c7933e6760fbc6 to your computer and use it in GitHub Desktop.
Save vinibgoulart/845aefd6cd5c086417c7933e6760fbc6 to your computer and use it in GitHub Desktop.
formik - get dirty values
const getDirtyValues = <T>(values, initialObject: T): object => {
const data = { ...values };
const keyValues = Object.keys(data);
const dirtyValues = keyValues.filter(
(keyValue) => data[keyValue] !== initialObject[keyValue],
);
keyValues.forEach((key) => {
if (!dirtyValues.includes(key)) delete data[key];
});
return data;
};
export { getDirtyValues };
@vinibgoulart
Copy link
Author

vinibgoulart commented Feb 24, 2023

example:

type PersonParams = {
  name: string;
  age: string;
};

const person = {
  name: 'vinicius',
  age: '19',
};

const Component = () => {
  const onSubmit = async (values: PersonParams) => {
    // age was changed, but the name is the same
    // { name: "vinicius", age: "20" }
    console.log(values);

    const payload = getDirtyValues<PersonParams>(values, initialValues);
    // { age: "20" }
    console.log(payload);
  }
  
  const formik = useFormik<PersonParams>({
    initialValues: {
      name: person.name,
      age: person.age,
    },
    onSubmit,
  });

  const { initialValues } = useFormik(formik)
};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment