0.7.16 • Published 1 year ago

@flatom/react v0.7.16

Weekly downloads
-
License
MIT
Repository
-
Last release
1 year ago

@flatom/react

React bindings package for Flatom store.

npm npm type definitions npm bundle size GitHub

Install

npm i @flatom/react

or

yarn add @flatom/react

@flatom/react depends on @flatom/core.

Usage

Step 1. Create store

// App
import React from 'react'
import { createStore } from '@flatom/core'
import { StoreProvider } from '@flatom/react'
import { Form } from './components/Form'

export const App = () => {
    // create statefull context for atoms execution
    const store = createStore();

    return (
        <div className="App">
            <StoreProvider value={store}>
                <Form/>
            </StoreProvider>
        </div>
    );
}

Step 2. Use in components

// components/Form

import { declareAction, declareAtom } from '@flatom/core'
import { useAction, useAtom } from '@flatom/react'

const changeName = declareAction();
const nameAtom = declareAtom<string>(
    'name',
    '',
    on => [
        on(changeName, (state, payload) => payload),
    ],
);

export const Form = () => {
    const name = useAtom(nameAtom);
    const handleChangeName = useAction(e => changeName(e.target.value));

    return (
        <form>
            <label htmlFor="name">Enter your name</label>
            <input id="name" value={name} onChange={handleChangeName}/>
        </form>
    );
}

Hooks Api

useAtom

Connects the atom to the store represented in context and returns the state of the atom from the store (or default atom state).

Basic (useAtom)

const atomValue = useAtom(atom);

Depended value by selector

const atomValue = useAtom(atom, atomState => atomState[props.id], [props.id]);

Mount without subscription (for subscribing atoms to actions)

const atomValue = useAtom(atom, () => null, []);

useAction

Binds action with dispatch to the store provided in the context.

Basic (useAction)

const handleDoSome = useAction(doSome);

Prepare payload for dispatch

const handleDoSome = useAction(value => doSome({ id: props.id, value }), [
  props.id,
]);

Conditional dispatch

If action creator don't return an action dispatch not calling.

const handleDoSome = useAction(payload => {
  if (condition) return doSome(payload);
}, []);
0.7.16

1 year ago

0.7.13

2 years ago

0.7.15

2 years ago

0.7.14

2 years ago

0.7.11

2 years ago

0.7.10

2 years ago

0.7.9

2 years ago

0.7.12

2 years ago

0.7.6

2 years ago

0.7.5

2 years ago

0.7.8

2 years ago

0.7.7

2 years ago

0.7.4

2 years ago

0.7.3

2 years ago

0.5.0

2 years ago

0.7.0

2 years ago

0.6.0

2 years ago

0.4.3

2 years ago

0.4.2

3 years ago

0.4.1

3 years ago

0.4.0

3 years ago

0.3.1

3 years ago

0.2.0

3 years ago

0.1.13

3 years ago