Skip to content

Instantly share code, notes, and snippets.

View ctrlplusb's full-sized avatar
📢

Sean Matheson ctrlplusb

📢
View GitHub Profile
const store = createStore<StoreModel>({
todos: {
items: ["Install easy-peasy", "Build app", "profit"],
// 👇
add: (state, payload) => {
state.items.push(payload);
}
},
notification: {
msg: "",
// 👇model to operate against
Action<TodosModel, string>;
// 👆payload
import { Action } from "easy-peasy";
type TodosModel = {
items: string[];
add: Action<TodosModel, string>; // 👈
}
type NotificationModel = {
msg: string;
set: Action<NotificationModel, string>; // 👈
store.getState().todos.items;
// ["Install easy-peasy", "Build app", "profit"]
@ctrlplusb
ctrlplusb / store.ts
Last active February 10, 2019 00:01
import { createStore } from 'easy-peasy';
import { StoreModel } from './model';
// 👇
const store = createStore<StoreModel>({
todos: {
items: ["Install easy-peasy", "Build app", "profit"]
},
notification: {
msg: ""
type TodosModel = {
items: string[];
}
type NotificationModel = {
msg: string;
}
export type StoreModel = {
todos: TodosModel;
import { select } from 'easy-peasy'; // 👈 import the helper
const store = createStore({
shoppingBasket: {
products: [{ name: 'Shoes', price: 123 }, { name: 'Hat', price: 75 }],
// 👇 define your derived state
totalPrice: select(state =>
state.products.reduce((acc, cur) => acc + cur.price, 0)
)
}
import { createStore, effect } from 'easy-peasy'; // 👈 import the helper
const store = createStore({
session: {
user: undefined,
// 👇 define your effectful action
login: effect(async (dispatch, payload, getState) => {
const user = await loginService(payload)
dispatch.session.loginSucceeded(user)
}),
import { useStore, useAction } from 'easy-peasy';
function TodoList() {
// 👇 Access state
const todos = useStore(state => state.todos.items)
// 👇 Access actions
const add = useAction(dispatch => dispatch.todos.add)
return (
<div>
{todos.map((todo, idx) => <div key={idx}>{todo.text}</div>)}
import { StoreProvider } from 'easy-peasy';
function App() {
return (
// 👇 secondly, surround your app with the provider to expose the store to your app
<StoreProvider store={store}>
<TodoList />
</StoreProvider>
);
}