โหมด Reducer

ใช้เมื่อการรวบรวมกฎการเปลี่ยนแปลงสถานะด้วย action ดีกว่าการเรียก setter โดยตรง


สถานะ reducer ที่ตั้งชื่อ

สร้างตัวลดระดับ Rxdispatch action โดยไม่เปลี่ยนแปลง state โดยตรง เหมาะสำหรับสถานะที่มีกฎการเปลี่ยนแปลงหลายอย่าง เช่น ตะกร้า, todo, editor state

tsx
type TodoAction =
  | { type: "add"; text: string }
  | { type: "toggle"; id: number }
  | { type: "clearDone" };

function todoReducer(state: TodoState, action: TodoAction): TodoState {
  switch (action.type) {
    case "add":
      return {
        items: [...state.items, { id: state.nextId, text: action.text, done: false }],
        nextId: state.nextId + 1,
      };
    case "toggle":
      return {
        ...state,
        items: state.items.map((item) =>
          item.id === action.id ? { ...item, done: !item.done } : item,
        ),
      };
    default:
      return state;
  }
}

const { dispatchTodo, useTodo } = createRxReducer(
  initialTodoState,
  todoReducer,
  "todo",
);

ใช้ reducer tuple helper สำหรับ runtime key

หากต้องแยก reducer store ตาม runtime key เช่น workspace id, project id createRxReducerTupleให้ใช้

tsx
export function useWorkspaceFilterState(workspaceId: string) {
  return createRxReducerTuple(
    initialFilterState,
    filterReducer,
    `workspace-filter:${workspaceId}`,
    { storage: "auto" },
  );
}