import { createModel } from 'daxus';
const model = createModel({ initialState });In Daxus, creating a model is the first step to utilize its functionality for managing data.
Specifies the initial state for your model.
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();This property determines how the accessor fetches data. It should return a promise.
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.
This function is called after a successful fetch.
This function is called upon a fetch failure.
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.
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).
model.getState();Retrieves the model's state.
model.invalidate();Marks all accessors generated by this model as stale.
Refer to this page for more details.