DEV Community

Cover image for Introduction to Jotai. Derived atoms. Data validation
Andrzej Fricze
Andrzej Fricze

Posted on

Introduction to Jotai. Derived atoms. Data validation

Read first part to know what's going on here.

You created first atom to hold your input text value. Then you created a derived atom that holds text length. Based on this code let’s create registration form, with basic validation.

First, let’s add label to your text input, so users know to put their name in there.

const nameAtom = atom("hello");

const Input = () => {
  const [text, setText] = useAtom(nameAtom);
  return (
    <div>
      <label>Name: </label>
      <input value={text} onChange={(e) => setText(e.target.value)} />
    </div>
  );
};

Enter fullscreen mode Exit fullscreen mode

Then take Input component and put it in Form component. Form component has a title and one input. Later we’ll add Error component there to show validation results.

const Form = () => {
  return (
    <form>
      <h1>Registration form</h1>
      <Input />
    </form>
  );
};
Enter fullscreen mode Exit fullscreen mode

Now create new, derived atom. Based on nameLengthAtom you check that name has at least 3 chars. If length is bigger, or equal, to 3, name is valid. Otherwise, it’s not.

const isNameValid = atom((get) => get(nameLengthAtom) >= 3);
Enter fullscreen mode Exit fullscreen mode

Use this new atom in Error component to show user whether name he typed in is valid. If name is valid don’t show anything. If name is invalid inform user that name has to be longer.

const Error = () => {
  const isValid = useAtomValue(isNameValid);
  return isValid ? 
      null : 
      <div style={{ color: "red" }}>Name is too short</div>;
};
Enter fullscreen mode Exit fullscreen mode

In this component you only read value from isNameValid atom, so you can use useAtomValue function, instead of useAtom. This is a more specialised version of useAtom. It gives access to value of atom, without exposing the ability to change atoms’ value. Using specialised API makes your code easier to understand, and more maintainable. const isValid = useAtomValue(isNameValid); is equal to const [isValid] = useAtom(isNameValid);

Now you’re ready to add Error component to Form component. This Form component can be used in your application.

const Form = () => {
  return (
    <form>
      <h1>Registration form</h1>
      <Input />
      <Error />
    </form>
  );
};

const App = () => (
  <Provider>
    <Container>
      <Form />
    </Container>
  </Provider>
);
Enter fullscreen mode Exit fullscreen mode

Check out this code live.

Check out Jotai website for docs and more examples of Jotai code.

Top comments (0)