Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to await a useDispatch value in React?

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 complete 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>
  );
}
like image 715
aks Avatar asked Nov 12 '19 20:11

aks


1 Answers

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

However, waiting for the component's props to update is a completely 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.

like image 166
markerikson Avatar answered Nov 09 '22 20:11

markerikson