teafuljs / teaful

🍵 Tiny, easy and powerful React state management

Home Page:https://npm.im/teaful

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Proposal: add setStore proxy

aralroca opened this issue · comments

Add setStore as a proxy:

const { useStore, getStore, setStore } = createStore({ example: 'example' })

// And with the possibility to use it everywhere, 
// without the need to use getStore to get the setter:
setStore.example('with another text')

currently this is possible with getStore (but with an extra uncomfortable step):

const { useStore, getStore } = createStore({ example: 'example' })

const [example, setExample] = getStore.example()
setExample('with another text')

Discussed in #76

Originally posted by yathink3 December 31, 2021


const Component = () => {
  const [state, setState] = useStateData({ name: '', age: 0 });
  const [count, setCount] = useState(0);
  const [isLoading, setIsLoading] = useState(false);
  const [isError, setIsError] = useState(false);

  const onChange = e => {
    const { name, value } = e.target;
    setState[name](value);
  };

  const onClick = () => {
    setCount(prev => prev + 1);
  };

  const onSubmit = e => {
    e.preventDefault();
    setIsLoading(true);
    setTimeout(() => {
      setIsLoading(false);
      setIsError(true);
    }, 2000);
  };

  return (
    <div>
      <h1>useStateData</h1>
      <form onSubmit={onSubmit}>
        <input type='text' name='name' value={state.name} onChange={onChange} />
        <input type='number' name='age' value={state.age} onChange={onChange} />
        <button type='submit'>Submit</button>
      </form>
      <p>{state.name}</p>
      <p>{state.age}</p>
      <p>{count}</p>
      <button onClick={onClick}>Click</button>
      {isLoading && <p>Loading...</p>}
      {isError && <p>Error!</p>}
    </div>
  );
};
```</div>