@jswork/use-active-state

React hook for active state.

Usage no npm install needed!

<script type="module">
  import jsworkUseActiveState from 'https://cdn.skypack.dev/@jswork/use-active-state';
</script>

README

use-active-state

React hook for active state.

version license size download

installation

npm install -S @jswork/use-active-state

usage

import React from 'react';
import useActiveState from '@jswork/use-active-state';
import styled from 'styled-components';

const Container = styled.div`
  width: 40%;
  min-width: 400px;
  margin: 30px auto 0;
  padding: 50px;
  border: 1px solid #ccc;
  .row {
    display: flex;
    margin-bottom: 10px;
    strong {
      display: inline-block;
      width: 120px;
    }
  }

  .result {
    background: #eee;
    padding: 20px;
    border: 1px dashed #f60;
    margin-top: 10px;
  }
`;

export default (props: any) => {
  const { state, sync, get, $ } = useActiveState(() => {
    console.log('state:', state, get('username'));
  });

  console.log('state:', state);

  return (
    <Container>
      <form autoComplete="off">
        <label className="row">
          <strong>username:</strong>
          <input type="text" name="username" onChange={sync()} />
        </label>
        <label className="row">
          <strong>email:</strong>
          <input type="text" name="email" onChange={sync()} />
        </label>
        <label className="row">
          <strong>password:</strong>
          <input type="password" name="password" onChange={sync()} />
        </label>
        <div className="actions">
          <button type="button">Submit</button>
          <button type="button" onClick={e => {
            $.reset();
          }}>reset</button>
        </div>
      </form>

      <div className="result">
        <pre>
          <code>{JSON.stringify(state, null, 2)}</code>
        </pre>
      </div>
      <div className="result">
        <pre>
          <code>isTouched: {String($.touched())}</code>
        </pre>
      </div>
    </Container>
  );
};

preview

license

Code released under the MIT license.