state management for applications
This library handles state a little differently than you might be accustomed to in your day-to-day frontend development, especially if you do a lot of coding with Redux. To some extent we like Redux, at least we like the features it offers such as having an immutable application state and allowing for a way to walk through and replay changes in your application. However, for our purposes it is too verbose and makes the developer think about things that they should not care about. The developer should only worry about his application such as building a login form or a sign in page and not about how to manage a full update cycle of application states and dispatch events for various components.
What we have tried to achieve with this library is the following architectural design goals.
a State is the single source of truth for applications, states can have views which are slices into your state that are used to update the main state.
const TODO_LIST_NAME = "todo_list";
interface ITodo {
id: number;
text: string;
}
interface ITodoList {
list: ITodo[];
}
const todoListInitalState: ITodoList = {
list: [],
};
function TodoListFromJSON(json: IJSONObject): ITodoList {
return {
list: (json.list as Array<IJSONObject>).map((json) => ({
id: json.id as number,
text: json.text as string,
})),
};
}
const state = new State(
{
[TODO_LIST_NAME]: todoListInitalState,
},
{
[TODO_LIST_NAME]: TodoListFromJSON,
}
);
const todoList = state.getStore(TODO_LIST_NAME);
const createTodo = (text: string) => {
const id = createId();
todoList.update(
(state) => ({
...state,
list: [...state.list, { id, text }],
}),
"create"
);
return id;
};
const removeTodoById = (id: number) =>
todoList.update((state) => {
const index = state.list.findIndex((todo) => todo.id === id);
if (index === -1) {
return state;
} else {
const newList = state.list.slice();
newList.splice(index, 1);
return { ...state, list: newList };
}
}, "remove");
Generated using TypeDoc