最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to await a useDispatch value in React? - Stack Overflow

programmeradmin2浏览0评论

In my React codebase I've integrated Redux usign react-redux and I'm using the useDispatch hook to dispatch actions from my views. I just have one problem I don't have access to the updated values just after updating the store. Is there a way for me to wait for the state update to plete like await or something like a callback where I can execute the other code?

This is how my code looks like:

import React from 'react';
import { useDispatch } from "react-redux";
import { setCore } from "../store/global";

// the value from the store is drilled down as props
export default function Home({ instance, core }) {
  const dispatch = useDispatch();

  const onConnect = async () => {
    // core may have some value before but I want to clear
    console.log(core); // prints the old value
    await dispatch(setCore(null));
    console.log(core); // Need to have null here
  }

  return (
    <div>
      <button onClick={onConnect}>Connect</button>
    </div>
  );
}

In my React codebase I've integrated Redux usign react-redux and I'm using the useDispatch hook to dispatch actions from my views. I just have one problem I don't have access to the updated values just after updating the store. Is there a way for me to wait for the state update to plete like await or something like a callback where I can execute the other code?

This is how my code looks like:

import React from 'react';
import { useDispatch } from "react-redux";
import { setCore } from "../store/global";

// the value from the store is drilled down as props
export default function Home({ instance, core }) {
  const dispatch = useDispatch();

  const onConnect = async () => {
    // core may have some value before but I want to clear
    console.log(core); // prints the old value
    await dispatch(setCore(null));
    console.log(core); // Need to have null here
  }

  return (
    <div>
      <button onClick={onConnect}>Connect</button>
    </div>
  );
}
Share Improve this question asked Nov 12, 2019 at 20:10 aksaks 9,49112 gold badges52 silver badges81 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 14

Dispatching by default is 100% synchronous. There's no need to wait for the dispatch itself.

However, waiting for the ponent's props to update is a pletely different question. Given that code, core will never update, because the definition of onConnect has already captured the value of core at the time the function was defined.

You may want to move that portion of the logic into a useEffect() hook that will trigger when the value of core has changed.

发布评论

评论列表(0)

  1. 暂无评论