Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ability to supply a data-save-bar's dirty status #437

Open
nick-potts opened this issue Oct 4, 2024 · 0 comments
Open

Ability to supply a data-save-bar's dirty status #437

nick-potts opened this issue Oct 4, 2024 · 0 comments

Comments

@nick-potts
Copy link

I'd like to be able to show the save bar when a user tries to save an invalid value. Currently if the user submits an invalid combination, the form will show errors, but the bar will disappear and the user can leave the page. In this case, the data was never persisted, so its not possible for them to know it has issues.

Also in other situations, its sometimes easier to manage the state of a form not in the DOM, especially in the case of arrays.

Manually supplying if a form is dirty would be a massive upgrade.

Alternative tried

For arrays, I've got this dumb helper:

export function HiddenArrayInput<T>({
  original,
  current,
}: {
  original: T[];
  current: T[];
}) {
  const id = useId();
  const ref = useRef<HTMLInputElement>(null);

  useEffect(() => {
    // compare it to the default value
    const originalValue = original
      .map((item) => {
        return JSON.stringify(item);
      })
      .join(",");
    const currentValue = current
      ?.map((item) => {
        return JSON.stringify(item);
      })
      .join(",");

    if (originalValue === currentValue) {
      return;
    }

    // any time the value changes, fire aaaan event
    const event = new Event("input", {
      bubbles: true,
    });
    ref.current?.dispatchEvent(event);
  }, [id, current, original]);

  return (
    <input
      hidden
      ref={ref}
      id={id}
      readOnly={true}
      value={current
        ?.map((item) => {
          return JSON.stringify(item);
        })
        .join(",")}
    />
  );
}

for errors, I've got this helper:

...
if (res.status === 422) {
    if (ref.current) {
        setHiddenValue(Math.random().toString());
    }
}
...

    const hiddenId = useId();
    const hiddenInput = <input
        hidden
        id={hiddenId}
        readOnly={true}
        ref={ref}
        value={hiddenValue}
    />;
    useEffect(() => {
        const event = new Event("input", {
            bubbles: true,
        });
        ref.current.dispatchEvent(event);
    }, [ref, hiddenValue]);
@nick-potts nick-potts changed the title Ability to mark form as dirty after submit and show a save-bar. Ability to supply a data-save-bar's dirty status Oct 4, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant