developit/unistore

[Lack of Docs !] Where can I find a clear Doc to use it through multiple files ?

Mariodandre opened this issue · 2 comments

Hello

I cannot see a clear doc that explain how to use Unicorn through class component files ?
How can I do ?
I'am disappointed to find such a minimal and vague official doc...

There is nothing special about Unistore relating to files, it's just standard imports and exports like any other JavaScript code you might write. As for classes - unistore doesn't differentiate between class and function components, they work identically.

Here is a runnable/editable codesandbox containing the code below:
👉 https://codesandbox.io/s/unistore-preact-classes-j77uf

// index.js
import { render } from 'preact';
import createStore from 'unistore';
import { Provider } from 'unistore/preact';
import TodoList from './TodoList.js';

const store = createStore({ todos: [] });

render(
  <Provider store={store}>
    <TodoList />
  </Provider>,
  document.body
);
// actions.js
let idCounter = 0;

export const todoActions = {
  addTodo(state, text) {
    const todo = {
      id: ++idCounter,
      text
    };
    const todos = state.todos.concat(todo);
    return { todos }
  },
  removeTodo(state, id) {
    const todos = state.todos.filter(todo => todo.id !== id);
    return { todos };
  }
};
// TodoList.js
import { Component } from 'preact';
import { connect } from 'unistore/preact';
import { todoActions } from './actions.js';
import TodoItem from './TodoItem.js';

class TodoList extends Component {
  state = { newText: '' };
  
  add = e => {
    e.preventDefault();
    const { newText } = this.state;
    this.setState({ newText: '' });
    this.props.addTodo(newText);
  };

  handleChange = e => {
    this.setState({ newText: e.target.value });
  };

  render({ todos }, { newText }) {
    return (
      <div>
        <form onSubmit={this.add}>
          <input value={newText} onInput={this.handleChange} placeholder="Add Todo [enter]" />
        </form>
        <ul>
          {todos.map(todo => <TodoItem todo={todo} key={todo.id} />)}
        </ul>
      </div>
    );
  }
}

export default connect(['todos'], todoActions)(TodoList);
// TodoItem.js
import { Component } from 'preact';
import { connect } from 'unistore/preact';
import { todoActions } from './actions.js';

class TodoItem extends Component {
  remove = () => {
    const { todo, removeTodo } = this.props;
    removeTodo(todo.id);
  };

  render({ todo }) {
    return (
      <li>
        {todo.text}
        <button onClick={this.remove}></button>
      </li>
    );
  }
}

export default connect([], todoActions)(TodoItem);

That would be a great addition to the examples. You made it extremely clear!