Todos - Async
Let's add some asynchronous calls to the previous Todos example
State management usually gets very complicated when we need to build a realistic app, that for instance needs to make calls to a server API, therefore it needs to integrate the state with asynchronous calls. For this example we will use Conan's autoBind feature, which is fully described under Conan asynchronous state
Let's say our Todo app needs to make an API call to fetch the current todos, and to add and toggle a todo. We could easily think of embedding that logic in its own service class. We could model that as:
Js
Ts
export class TodoListServiceImpl {
fetch() {
return Asaps.delayed([{ description: 'test', id: '-1', status: ToDoStatus.PENDING }], 500, 'fetch');
}
addTodo(todo) {
return Asaps.delayed(todo, 5000, 'addTodo');
}
toggleTodo(todo) {
return Asaps.delayed(todo, 1000, 'toggleTodo');
}
}
export interface TodoListService {
fetch(): Asap<ToDo[]>;
addTodo(todo: ToDo): Asap<ToDo>;
toggleTodo(todo: ToDo): Asap<ToDo>;
}
export class TodoListServiceImpl implements TodoListService {
public fetch(): Asap<ToDo[]> {
return Asaps.delayed([{description: 'test', id: '-1', status: ToDoStatus.PENDING}], 500, 'fetch');
}
public addTodo(todo: ToDo): Asap<ToDo> {
return Asaps.delayed(todo, 5000, 'addTodo');
}
public toggleTodo(todo: ToDo): Asap<ToDo> {
return Asaps.delayed(todo, 1000, 'toggleTodo');
}
}
We are just simulating the API calls with a delayed Asap
Note the function names match the reducers names, therefore ConanJs will bind each funcrion with its corresponding reducer
As mentioned above we will be using autoBind, passing the todoListSevice implementation:
Js
Ts
export class TodoListAsyncStateFactory {
static create(todoListService) {
return Conan.state({
name: 'todos-async',
initialData: {
appliedFilter: VisibilityFilters.SHOW_ALL,
todos: []
},
reducers: TodoListReducersFn,
autoBind: todoListService
});
}
}
export class TodoListAsyncStateFactory {
static create(todoListService: TodoListService): TodoListState {
return Conan.state<TodoListData, TodoListReducers>({
name: 'todos-async',
initialData: {
appliedFilter: VisibilityFilters.SHOW_ALL,
todos: []
},
reducers: TodoListReducersFn,
autoBind: todoListService
})
}
}