How to get the changed state after an async action, using React functional hooks? I have found a redux solution for this issue, or a react class component solution, but I am wondering if there is a simple react functional solution.
Here is the scenario:
- create a functional react component with. few states
- create several button elements that each alter a different state.
- using one of the button elements, trigger an async action.
- If there was any other change in the state, prior to receiving results from the async function, abort all other continuing actions.
Attached is a code sandbox example https://codesandbox.io/s/magical-bird-41ty7?file=/src/App.js
import React, { useState } from "react";
import "./styles.css";
export default function App() {
const [counter, setCounter] = useState(0);
const [asyncCounter, setAsyncCounter] = useState(0);
return (
<div className="App">
<div>
<button
onClick={async () => {
//sets the asyncCounter state to the counter states after a 4 seconds timeout
let tempCounter = counter;
await new Promise(resolve => {
setTimeout(() => {
resolve();
}, 4000);
});
if (tempCounter !== counter) {
alert("counter was changed");
} else {
setAsyncCounter(counter);
}
}}
>
Async
</button>
<label>{asyncCounter}</label>
</div>
<div>
<button
onClick={() => {
//increases the counter state
setCounter(counter + 1);
}}
>
Add 1
</button>
<label>{counter}</label>
</div>
</div>
);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>