Lorese
Lorese is a really lightweight state manager for frontend applications. It uses a single store for caching the data, and it should considered the source of truth for your app.
It is compound by 3 main parts:
- LO - loaders: Allow to fetch data asynchronously, and returns an object that can be consumed directly in a declarative way.
- RE - reducers: Set the data in the store, updating the cache and emiting events to allow you refresh your UI.
- SE - selectors: Create selectors to access the data in the store. Best practice is not to allow your UI get the store directly, instead create selectors with logic reusable across your app.
How to use it
import Lorese from 'lorese';
const store = {
todoIds: null,
todos: {}
}
const stateManager = Lorese(store);
const {loader, selector, reducer} = stateManager;
const getTodos = selector( store => {
if( !store.todoIds ) return;
return store.todoIds.map( id => store.todos[id] );
})
const onTodosLoaded = reducer( (store, todoList) => {
let todoIds = [];
let todos = {...store.todos};
todoList.forEach( todo => {
ids.push(todo.id);
todos[todo.id] = todo;
})
return { todoIds, todos };
});
const loadTodos = stateManager.loader({
selector: getTodos,
async load(){
let todoList = await api.fetchTodos();
onTodosLoaded( todoList );
}
})
const {isLoading, data: todos} = loadTodos();
isLoading ? renderLoading() : renderTodos(todos);
Subscribe to changes in the store
const stateManager = Lorese(store);
function rerender(){ }
stateManager.addChangeListener( rerender );
stateManager.removeChangeListener( rerender );