Search code examples
javascriptreactjsreduxredux-toolkitredux-thunk

Can we access the response of a request inside asyncThunk without selector and without passing by store or state in redux toolkit


I'm wondering if there is a possibility In redux toolkit to access request response of an asyncThunk without passing by store or state or selector. Sometimes we wanna use the data received from a request to perform another request. So can we get the response request without waiting for state or store to update and without using useEffect.

I mean using response received from the asyncThunk in another request something like that: const {id} = await dispatch(getTest())

dispatch (getTestResultById(id))


Solution

  • Yes, if the first action is an asynchronous action/thunk then it can be awaited. Redux Toolkit thunks always resolve, so be sure to unwrap the returned resolved Promise to see if the action was successful or not.

    Example:

    const handler = async () => {
      try {
        const { id } = await dispatch(getTest()).unwrap();
    
        dispatch (getTestResultById(id));
      } catch(error) {
        // handle rejected Promise or any thrown exceptions
      }
    };
    

    For more details see Handling Thunk Results.