Store Commands

We define signals in todoStore to allow the mutation of the state stored in the Store.
This mutation occured through commands

A command allow a function to be executed when a signal is dispatch.

see Command in documentation for more details.

Command can be writen in the same file as the store or externalize. We will do both.

stores/todoStore.js

let's add the add command.

import { Store } from 'sinux';

const todoStore = new Store({todos:[]},
  'add',
  'remove',
  'update',
  'complete',
  'load',
);

todoStore.add.add((state, todo) => {...state, todos : [...state.todos, {text: todo, completed: false}] });

export default todoStore;

stores/todoLoad.js

Let's create the load command in a separate file.

import todoStore from './todoStore';

todoStore.load.add((state) => {
  var dummyData = {
    todos: [
      { text: "Learn how to use Sinux", completed: false }
    ]
  }
  return new Promise((resolve, reject) => {
    setTimeout(()=> resolve({...state, todos : [...state.todos, ...dummyData.todos]}), 1000)
  })
});

This command is asynchronous.

This is correct, but be sure to require this file to register the command. An index.js file in store folder will work.

stores/index.js

import todoStore from './todoStore';
import todoLoad from './todoLoad';

export {
  todoStore
};

then change the import in the container (containers/TodoApp.js)

import { todoStore } from '../stores';

stores/todoStore.js (final)

import { Store } from 'sinux';

const todoStore = new Store({todos:[]},
  'add',
  'remove',
  'update',
  'complete',
  'load',
);

// commands
todoStore.add.add((state, todo) => {
  return {...state, todos : [...state.todos, {text: todo, completed: false}]}
});
todoStore.remove.add((state, id) => {
  return {...state, todos : [...state.todos.slice(0, id), ...state.todos.slice(id + 1)]}
});
todoStore.update.add((state, id, todo) => {
  return {...state, todos : [...state.todos.slice(0, id), {...todo}, ...state.todos.slice(id + 1)]}
});
todoStore.complete.add((state, id) => {
  let todo = {...state.todos[id]}
  todo.completed = true;
  return {...state, todos : [...state.todos.slice(0, id), {...todo}, ...state.todos.slice(id + 1)]}
});

export default todoStore;

results matching ""

    No results matching ""