DEV Community

Xuan
Xuan

Posted on

Lazy Model in Daxus

In Daxus, developers have the flexibility to manage state updates themselves, allowing for customized state structures such as pagination for a single source of truth. However, not all data requires a custom data structure. For most data, we simply need to record the fetched data without worrying about how it is synced to the model's state.

To simplify the code required for such scenarios, Daxus introduces a new feature called "Lazy Model". Let's explore how to use this feature.

Creating a Lazy Model

const lazyModel = createLazyModel();

const getUser = lazyModel.defineNormalAccessor<string, User>({
  fetchData: async (userId) => {
    return getUserApi(userId);
  },
});

function useUser(userId: string) {
  return useLazyAccessor(getUser(userId));
}
Enter fullscreen mode Exit fullscreen mode

When using createLazyModel, there's no need to provide an initial state, and you don't have to create an adapter since you don't need to manage how the fetched data is synced to the model's state.

It is recommended to use the useLazyAccessor hook with accessors defined using the lazy model. This hook allows easy access to the cached data without the need for a getSnapshot function. However, if desired, you can still provide a getSnapshot function to select specific data:

function useUserName(userId: string) {
  return useLazyAccessor(getUser(userId), (user) => user?.name);
}
Enter fullscreen mode Exit fullscreen mode

Mutating Data

The lazy model also provides a mutate method, but it functions slightly differently from the original model. Developers need to provide an accessor to access the corresponding cached data:

lazyModel.mutate(getUser(userId), (prevUser) => {
  return { ...prevUser, name: 'new user name' };
});
Enter fullscreen mode Exit fullscreen mode

Note that when using the lazy model, it is important to return a new data object instead of directly mutating the cached data.

Retrieving State

To retrieve the cached state, you can use the getState method with the corresponding accessor:

lazyModel.getState(getUser(userId)); // Returns User | undefined
Enter fullscreen mode Exit fullscreen mode

Limitations

When using the lazy model, there is a trade-off in terms of control over the model's state. The data is bound to the accessor, and its definition is derived from the return value of the fetchData function.

It is recommended to use only one lazy model in your app and avoid using accessors generated by a normal model with the mutate or getState methods. These methods have different internal behaviors and may not function as expected when used with accessors from other models.

Top comments (0)