Todos - Optimistic

What if we wanted to optimistically add/toggle our todos before the server API call returns?

Introduction

ConanJs allows you to add optimistic updates to your state. In order to achieve this, it provides State monitor and asyncMerge. As you will see, the monitor also allows us to cancel ongoing async calls, and update our local state accordingly.

Adding the state

We need to slightly modify our Todo definition to make it optimistically updatable. It just needs to hold a status per todo item:

export enum OptimisticStatus {
    SETTLED = 'SETTLED',
    IN_PROCESS = 'IN_PROCESS',
}

export interface OptimisticData<T> {
    data: T;
    status: OptimisticStatus;
    cancelCb: ICallback;
}

export interface OptimisticTodoListData {
    todos: OptimisticData<ToDo>[];
    appliedFilter: VisibilityFilters;
}

Now we will enrich our app with a new optimistically updatable state. For that in our Conan's DI definition file, we have to add:

Implement optimistic updates

The key part here is how the optimisticTodoListState is created, as it is in fact a merged state of the state's monitor info and the state's data:

Adding cancellation

As the app can now access a merged state that also contains the monitor actions, it can invoke the cancel action. For example, we have slightly modified the Todo react component, to include a loading... and a cancel button:

Getting the code

Please feel free to visit our examples at:

or the code sandbox below, for more details on this ConanJs feature.

Code sandbox

These TODOs are very optimistic!

Last updated

Was this helpful?