Skip to content

Instantly share code, notes, and snippets.

@ctrlplusb
Last active November 5, 2018 20:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ctrlplusb/59a0f1573777bebed87ce375aa7d69ac to your computer and use it in GitHub Desktop.
Save ctrlplusb/59a0f1573777bebed87ce375aa7d69ac to your computer and use it in GitHub Desktop.
Easy Peasy Primary API
import { StoreProvider, createStore, useStore, useAction } from 'easy-peasy';
// ๐Ÿ‘‡ firstly, create your store by providing your model
const store = createStore({
todos: {
items: ['Install easy-peasy', 'Build app', 'Profit'],
// ๐Ÿ‘‡ define actions
add: (state, payload) => {
state.items.push(payload) // ๐Ÿ‘ˆ you mutate state to update (we convert
// to immutable updates)
}
}
});
function App() {
return (
// ๐Ÿ‘‡ secondly, surround your app with the provider to expose the store to your app
<StoreProvider store={store}>
<TodoList />
</StoreProvider>
);
}
function TodoList() {
// ๐Ÿ‘‡ finally, use hooks to get state or actions. your component will receive
// updated state automatically
const todos = useStore(state => state.todos.items)
const add = useAction(dispatch => dispatch.todos.add)
return (
<div>
{todos.map((todo, idx) => <div key={idx}>{todo.text}</div>)}
<AddTodo onAdd={add} />
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment