1.0.0 • Published 3 years ago

elementos-react v1.0.0

Weekly downloads
1
License
MIT
Repository
github
Last release
3 years ago

elementos-react

React bindings for elementos

NPM JavaScript Style Guide

Install

npm install --save elementos-react

Please see the full documentation!

Basic Usage

Open in CodeSandbox

import React from 'react';
import { 
  Button, 
  Flex, 
  FormControl, 
  FormLabel, 
  Input,
  Stack
} from "@chakra-ui/react";
import { atom, molecule, observe } from 'elementos';
import { useConstructor, useObservable } from 'elementos-react';
import * as api from "./api";

function LoginForm(props) {
  const { 
    formEl$, 
    form$, 
    submitting$ 
  } = useConstructor(({ beforeUnmount }) => {
    const formEl$ = atom(null);
    const submitting$ = atom(false);
    const form$ = molecule({
      username: atom(""),
      password: atom(""),
      formEl$
    });

    beforeUnmount(
      // log whenever formEl changes
      observe(formEl$, (formEl) => {
        console.log(formEl)
      })
    )

    beforeUnmount(
      observe(form$, (form) => {
        console.log(form)
      })
    )
    
    return {
      formEl$,
      form$,
      submitting$
    };
  });

  const form = useObservable(form$);
  const submitting = useObservable(submitting$);

  const handleSubmit = (e) => {
    e.preventDefault();
    submitting$.actions.set(true);
    api.logIn(form).finally(() => {
      submitting$.actions.set(false);
    });
  };

  return (
    <Stack ref={formEl$.actions.set} as="form" spacing={4} onSubmit={handleSubmit}>
      <FormControl id="username">
        <FormLabel>Username</FormLabel>
        <Input
          type="text"
          value={form.username}
          onChange={(e) => {
            form$.children.username.actions.set(e.target.value);
          }}
        />
      </FormControl>
      <FormControl id="password">
        <FormLabel>Password</FormLabel>
        <Input
          type="password"
          value={form.password}
          onChange={(e) => {
            form$.children.password.actions.set(e.target.value);
          }}
        />
      </FormControl>
      <Button isLoading={submitting} type="submit">
        Submit
      </Button>
    </Stack>
  );
}

License

MIT © malerba118

1.0.0

3 years ago