Skip to content

Latest commit

 

History

History
115 lines (80 loc) · 2.65 KB

createModel.md

File metadata and controls

115 lines (80 loc) · 2.65 KB

createModel

import { createModel } from 'daxus';

const model = createModel({ initialState });

In Daxus, creating a model is the first step to utilize its functionality for managing data.

Options

initialState

Specifies the initial state for your model.

Methods

defineAccessor

const accessorCreator = model.defineAccessor<Data, Arg = void, E = any>({
  async fetchData(arg, { getState }) {
    return apiCall(arg);
  },
  syncState(draft, { arg, data }) {
    draft.data = data;
  },
  onSuccess({ data, arg }) {
    // perform side effects upon successful fetching
  },
  onError({ error, arg }) {
    // perform side effects upon fetching failure
  }
});

The result of defineAccessor is an accessor creator object. This object is used primarily to create an accessor and then apply it in the useAccessor hook.

useAccessor(accessorCreator(arg), getSnapshot);

You can also utilize it to invalidate the accessors created by it:

accessorCreator.invalidate();

fetchData

This property determines how the accessor fetches data. It should return a promise.

syncState

This property dictates how the model's state is synchronized after a successful fetch. You can directly modify the draft since Daxus use immer internally.

onSuccess

This function is called after a successful fetch.

onError

This function is called upon a fetch failure.

defineInfiniteAccessor

const accessorCreator = model.defineInfiniteAccessor<Data, Arg = void, E = any>({
  async fetchData(arg, { getState, pageIndex, previousPage }) {
    return apiCall(arg);
  },
  syncState(draft, { arg, data, pageIndex, pageSize }) {
    draft.data = data;
  },
  onSuccess({ data, arg }) {
    // perform side effects upon successful fetching
  },
  onError({ error, arg }) {
    // perform side effects upon fetching failure
  }
});

This method is almost identical to the defineAccessor method, but the fetchData function's context includes pageIndex and previousPage, and the syncState function's context includes pageIndex and pageSize.

mutate

model.mutate(draft => {
  draft.data = { ...newData };
}, serverStateKey);

Use this method to directly modify the model's state. Note that when using useHydrate, you should provide a server state key. For more information, refer to Server-Side Rendering (SSR).

getState

model.getState();

Retrieves the model's state.

invalidate

model.invalidate();

Marks all accessors generated by this model as stale.

Auto Model

Refer to this page for more details.