DEV Community

Nguyễn Hữu Hiếu
Nguyễn Hữu Hiếu

Posted on

react use-zustand demo

import { Input } from "@/components/ui/input";
import { create } from "zustand";

interface UserFormState {
  username?: string;
  mobile?: string;
  gmail?: string;
}

const initState: UserFormState = {
  username: "",
  mobile: "",
  gmail: "",
};

const useUserForm = create<UserFormState>(() => ({
  ...initState,
}));

const setUsername = (setUsername: string) =>
  useUserForm.setState({ username: setUsername });

const setMobile = (setMobile: string) =>
  useUserForm.setState({ mobile: setMobile });

const setGmail = (setGmail: string) =>
  useUserForm.setState({ gmail: setGmail });

const UsernameInput = () => {
  const username = useUserForm((state) => state.username);
  return (
    <div>
      <label>UsernameInput</label>
      <Input
        type="text"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
      />
    </div>
  );
};

const MobileInput = () => {
  const mobile = useUserForm((state) => state.mobile);
  return (
    <div>
      <label>MobileInput</label>
      <Input
        type="text"
        value={mobile}
        onChange={(e) => setMobile(e.target.value)}
      />
    </div>
  );
};

const GmailInput = () => {
  const gmail = useUserForm((state) => state.gmail);
  return (
    <div>
      <label>GmailInput</label>
      <Input
        type="text"
        value={gmail}
        onChange={(e) => setGmail(e.target.value)}
      />
    </div>
  );
};

export const Demo001Zustand = () => {
  return (
    <>
      <h2>Demo001Zustand.tsx</h2>
      <UsernameInput />
      <MobileInput />
      <GmailInput />
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)