3217

React Hooks - useReducer: Wait for reducer to finish before triggering a function

<h3>Question</h3>

I have the component using useReducer Hooks:

const init = { statA: true, statB: true }; const reducer = (state, action) => { switch (action.type) { case "ActionA": return { ...state, statA: !state.statA }; case "ActionB": return { ...state, statB: !state.statB }; default: return state; } }; const App = () => { const [state, dispatch] = useReducer(reducer, init); const clickMe = () => { dispatch({ type: "ActionA" }); dispatch({ type: "ActionB" }); console.log(state); } return( <button onClick={() => clickMe()}>Click Me</button> ); };

When the button is clicked, the state will be changed. But when I view the log, it prints the previous state, not the current updated state.

//On the first click //Expected { statA: false, statB: false } //Reality { statA: true, statB: true } //On the second click //Expected { statA: true, statB: true } //Reality { statA: false, statB: false }

I know that with setState, I can use callback to work with updated state. But with useReducer, I don't know how to work with the updated state. Is there any way to solve my problem?


<h3>Answer1:</h3>

console.log(state) is side effect. Side effects belong to useEffect hook:

const [state, dispatch] = useReducer(reducer, init); useEffect(() => { // a condition may be added in case it shouldn't be executed every time console.log(state); }, [state]); const clickMe = () => { dispatch({ type: "ActionA" }); dispatch({ type: "ActionB" }); }
<h3>Answer2:</h3>

If a library does not expose a certain functionality, this could mean that it is not supposed to be used in the way you want it. That setState takes a callback, while Hooks do not is probably a design decision.

If you want to trigger a side effect when the state changes, do that in the reducer itself:

const reducer = (state, action) => { switch (action.type) { case "ActionA": console.log("action a triggered"); // <<< return { ...state, statA: !state.statA }; case "ActionB": return { ...state, statB: !state.statB }; default: return state; } };

Or if you just want to debug the state, do that when the App gets rerendered:

const [state, dispatch] = useReducer(reducer, init); console.log(state);

来源:https://stackoverflow.com/questions/55559307/react-hooks-usereducer-wait-for-reducer-to-finish-before-triggering-a-functio

Recommend

  • Wordpress PHP within PHP
  • visual studio (SSDT) 2017 unable to start debugging
  • How to add dynamic filter drop down using Jqgrid?
  • How to implement a callback method within DLL (Delphi / TJVPluginManager + TJvPlugin)
  • How to install PyGObject through PyCharm
  • Jaccard Similarity of an RDD with the help of Spark and Scala without Cartesian?
  • Alternative to __del__ for final result & killing processes in a class?
  • Google Data Studio MySql data source connection does not exist Error
  • Use Perl to Add GIF Image Other Than 8-bit to PDF
  • Application backgrounding in Xamarin.Mac
  • Sharing multiple images on facebook post
  • Laravel 5.7: Custom blade template for Maintenance Mode but not 503.blade.php
  • Making query to find nearest multiple(Lat,Long) from the single(Lat,Long)
  • async GET request with body from browser
  • android check if file exists with case sensitivity?
  • can you use embedded ruby in custom javascript files in rails?
  • How to get “crispEdges” for SVG text?
  • Authorize Attribute Authentication with Postman in Web Api
  • How to use array in autohotkey?
  • Copy and paste data from multiple workbooks to a worksheet in another Workbook
  • Generate and export point cloud from Project Tango
  • how to specify different css for ie
  • How can i move Clearcase dyamic/snapshot views to another host (Linux)
  • Multiplying polynomials/simplifying like terms
  • Tensorflow Dataset API restore Iterator after completing one epoch
  • using maven pom while creating jar:test-jar some times it says JAR will be empty - no content was ma
  • VS2010 RDLC C#. How can I set a LocalReport object to a ReportViewer?
  • JavaScript Regex to Match Boundaries of Words with diacritics
  • How to turn off notice reporting in xampp?
  • How to use Streams api peek() function and make it work?
  • Using redis as an LRU cache for postgres
  • How to use FirstOrDefault inside Include
  • PHP Permalinks.. how to change?
  • Spring Boot not autowiring @Repository
  • Running R's aov() mixed effects model from Python using rpy2
  • ReferenceError: TextEncoder is not defined