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

huangapple go评论114阅读模式
英文:

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

问题

我想知道在redux toolkit中是否有可能在不经过store、state或selector的情况下访问asyncThunk的请求响应。有时候我们想要使用从一个请求接收到的数据来执行另一个请求。所以我们能否在不等待state或store更新,也不使用useEffect的情况下获取响应请求呢?

我的意思是在另一个请求中使用从asyncThunk接收到的响应,就像这样:
const {id} = await dispatch(getTest())

dispatch(getTestResultById(id))

英文:

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))

答案1

得分: 1

是的,如果第一个操作是异步操作/异步函数,那么它可以被等待。Redux Toolkit的thunk始终会解析,所以请确保解开返回的解析后的Promise,以查看操作是否成功。

示例:

const handler = async () => {
  try {
    const { id } = await dispatch(getTest()).unwrap();

    dispatch(getTestResultById(id));
  } catch(error) {
    // 处理被拒绝的Promise或任何抛出的异常
  }
};

更多详细信息请参见处理Thunk结果

英文:

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.

huangapple
  • 本文由 发表于 2023年7月27日 14:59:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76777203.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定