简体   繁体   中英

How to trigger action inside redux dispatch?

I've got an problem with redux. Here is my code:

actions.ts

export const getOrders = (id: string) => {
    return async (dispatch) => {
        const queryParams = {
            id,
            search: null,
            order: "DESC",
            status: "all"
        };

        const orders = await api.get('/api/orders', queryParams);
        dispatch(getOrdersSuccess(orders));
    }
}

export const getOrdersSuccess= (payload) => {
    return {
        type: 'GET_ORDERS_SUCCESS',
        payload
    };
}

someComponent.ts

  useEffect(() => {
      dispatch(getOrders(id)); //here is problem
  }, [dispatch, id])

can someone tell me why I cannot use getIncidents(id) function inside dispatch ? When I put this function, VSCode throw me this error:

Argument of type '(dispatch: any) => Promise<void>' is not assignable to parameter of type 'AnyAction'.
  Property 'type' is missing in type '(dispatch: any) => Promise<void>' but required in type 'AnyAction'.ts(2345)

I have no idea how to fix this :/

thanks for any help!

Try waiting for promise to resolve , then dispatch your actions:

async/await :

 useEffect(() => { ( async function handleAsync() { let order = await getOrders(id) dispatch(order); } )() }, [dispatch, id])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM