useConsumeOrders.ts 1.36 KB
Newer Older
姜雷 committed
1
import { useEffect } from '@tarojs/taro';
姜雷 committed
2 3
import { fetchAllOrder } from '@/api/order';
import { AllOrderItem } from '@/types/Order/Order';
姜雷 committed
4 5 6 7 8 9 10
import { useSelector, useDispatch } from '@tarojs/redux';
import { OrderStoreState } from './store';
import {
  appendConsumeOrders,
  updateConsumeOrders,
  updateConsumeLastId,
} from './actions';
11

姜雷 committed
12
const useConsumeOrders = (
13 14
  customerId: number,
  pageSize: number,
姜雷 committed
15
): [AllOrderItem[], () => Promise<any>, () => Promise<any>] => {
姜雷 committed
16 17 18 19 20
  const state = useSelector(
    (state: { OrderList: OrderStoreState }) => state.OrderList.consume,
  );
  const dispatch = useDispatch();

姜雷 committed
21
  const fetchData = (customerId: number, pageSize: number) =>
姜雷 committed
22
    fetchAllOrder({
23
      customerId,
姜雷 committed
24
      lastOrderId: state.lastOrderId,
25 26 27
      pageSize,
    })
      .then(res => {
姜雷 committed
28
        state.lastOrderId
姜雷 committed
29 30
          ? dispatch(appendConsumeOrders(res.data))
          : dispatch(updateConsumeOrders(res.data));
31 32 33 34 35
        return res.data;
      })
      .catch(err => {
        console.log(err);
      });
姜雷 committed
36
  const fetchMore = () => {
姜雷 committed
37
    return fetchData(customerId, pageSize);
姜雷 committed
38 39 40
  };
  const resetOrders = () => {
    dispatch(updateConsumeLastId(0));
姜雷 committed
41
    return fetchData(customerId, pageSize);
姜雷 committed
42
  };
43 44

  useEffect(() => {
姜雷 committed
45 46
    fetchData(customerId, pageSize);
  }, [customerId, pageSize]);
47

姜雷 committed
48
  return [state.consumeOrders, fetchMore, resetOrders];
49 50
};

姜雷 committed
51
export default useConsumeOrders;