Skip to content

Latest commit

 

History

History
55 lines (30 loc) · 2.99 KB

async-setting-and-retrieval.md

File metadata and controls

55 lines (30 loc) · 2.99 KB

Async: Setting and retrieval of state

Scenarios: Every click counts (e.g. in a game or a real-time trading app). Even if the server lags, I want every interaction to be counted.

We look at two cases in which time lags of asynchronous actions (mostly API calls) can cause issues.

[Case 1] Async setting of state

Problem: CodeSandBox: Async setting of state (problem) - observe the issue

  • Closure in action: count is frozen at the value of the first render.
  • Setter of state is in an asynchronous function (setTimeout).

Non-ideal solution: CodeSandBox: Async setting of state (non-ideal solution)

Solution: CodeSandBox: Async setting of state with functional updater form

[Case 2] Async retrieval of state

Let's look at this similar case:

Problem: count freezes

Problem description:

  • Issue: count gets frozen and subsequent changes during the async setTimeout call are ignored in alert.
  • Can this issue be solved with the updater function? - Try it!

Solution: use helper variable

Task: What is going on in here?

These CodeSandBoxes contain the solution without explanations:

Solution: Closure in action!

These CodeSandBoxes contain explanations:

Note: The issue is not solved by switching from a primitive data type to a complex data type