vantezzen / auto-form

🌟 A React component that automatically creates a @shadcn/ui form based on a zod schema.
https://vantezzen.github.io/auto-form/
MIT License
2.75k stars 99 forks source link

Clear form input on submit #42

Closed ItsMeViipeR closed 11 months ago

ItsMeViipeR commented 11 months ago

How to clear the input after submiting the stuff?

<AutoForm formSchema={formSchema} onSubmit={addTodo}>
    <AutoFormSubmit />
</AutoForm>

const [todos, setTodos] = useState([] as Todo[]);
  const [done, _setDone] = useState(false);
  const [loading, setLoading] = useState(true);

  const loadTodos = () => {
    const storedTodos = JSON.parse(localStorage.getItem("todos") || "[]");
    setTodos(storedTodos);
    setLoading(false);
  };

  useEffect(() => {
    loadTodos(); // Appel de la fonction pour charger les todos depuis le stockage local
  }, []);

  function addTodo(event: TodoFormResult) {
    // Add the new todo to the list
    const newTodo = { text: event.todo, done, id: Date.now() };
    const updatedTodos = [...todos, newTodo];
    setTodos(updatedTodos);

    // Save the updated list to local storage
    localStorage.setItem("todos", JSON.stringify(updatedTodos));
  }
vantezzen commented 11 months ago

You should be able to use the controlled form data (https://github.com/vantezzen/auto-form#controlled-form) to clean and modify fields

ItsMeViipeR commented 11 months ago

But that doesn’t explain how to delete the input content.

vantezzen commented 11 months ago

You should be able to do something like:

const formSchema = z.object({
  username: z.string()
});

const [values, setValues] = useState<Partial<z.infer<typeof formSchema>>>({});

<AutoForm values={values} onValuesChange={setValues} 
onSubmit={() => {
  setValues({
    username: "",
  });
}}
/>;