Reactjs, strange behavior on checking state value (again) - reactjs

Ok, there is something I don't understand again:
onDateChange(child, performUpdate){
console.log("child", child, child.state);
}
As you can see, from the debugeur, the state has some value. But when I try to access them, they act like if they where not initialized. Like if the setState wasn't an atomic operation after all...
Actually I don't have any idea as it seems counter intuitive.
Can someone help me to get my data from the callback. Every operation in js/reactjs act differently from what it is expected.
Is that because the 'state' property is in another field and duplicated? I can't find any logical reason for this strange behavior.
edit:
So it appear that setState is asynchronuous. And worst part, non atomic operation. This is kind of strange they don't speak of that in the documentation (instead they said to not use state directly but by method call. Why? Because they do the change in another thread without telling the client!!!).
So this is how you have concurrency problem like I had.
Is there a clean approach for this kind of problem? Like a callback on setState method when all the operation are done (some people use delay or inline function, which absolutly don't correct the problem ).
To resolve my issue, I had to use a proxy pattern where there is the datastructure independantly from the view who display it, and act as if it was the same object. So that the controller don't have to deal with all this 'background' threaded operation mess. (Note: the datastructure is not a model, but a readonly object).

Related

Inspect Flink operator state in unit tests

Using Flink's test harness classes to test my stateful operator, I want to write unit tests that verify that the data that is stored in the operator state is what I expect. However, it seems that I'm not able to do this, and can only call getOuput to see what the operator has output and numKeyedStateEntries to see how many values are in the state. Is there a way to actually get the values of what is in the state?
There's no (reasonable) way to do that.
You could, hypothetically, write a test that takes a savepoint and then uses the State Processor API to verify the state.
I might argue that testing the values stored in the state would couple the tests too closely to the implementation. Verifying that the results are correct and that state isn't being retained overly long should be enough. But I can agree that having more visibility into the state backend during unit testing would be nice.
First off, I agree with David's comment about how inspecting state creates a tight coupling with implementation. Though sometimes that's useful, if you have complex behavior for setting and/or updating state.
In any case, I believe there is another (unreasonable) way to do this...
Create a MyStateBackend class that extends HashMapStateBackend.
In this class you override createKeyedStateBackend, and save the result (it's a HeapKeyedStateBackend).
Add a getStates() method that returns List<Tuple2<K, V>> which are the keyed state values, by calling the saved backend's getKeys() and getOrCreateKeyedState() methods.
When you set up your test harness, call harness.setStateBackend(your custom state backend) before calling harness.setup() and harness.open().
You should now be able to get/inspect the state.

Is it always necessary to add all used functions within useEffect to its dependencies array?

I am currently building a Tetris game on React just to practice hooks (used to develop in class components back in the day, kind of left React for a while and yesterday I decided to use it once again).
The game is working perfectly well, and it behaves as expected on each and every situation, however, there is a constant warning related to using a function within useEffect without it being a dependency.
To clarify - I have a useEffect function that all it does is call an updateFunction and is dependent just on the x and y coordinates of the moving Tetris block. The update function updates the state of the board whenever the position of the shape changes.
I know that React re-creates functions on each and every render, but giving a useCallback to the update function would cause it to be re-created endlessly (as then, the complier would ask me to make it dependent on the board state, thus each time it updates the board, it'll be forced to be re-created once again), and this causes an infinite loop of rendering.
Is it really necessary to put every function within useEffect as a dependency, even if said functions only causes a visual rendering to show the current state of the game?
You can always put whole function inside useEffect and you want get this error and problem
Someone just asked the similar question, and my answer is there, React won't let me use `useEffect` in a completely reasonable way
The answer to your question is that, no you don't have to, if the warning doesn't bother you, and your code is still working, then move on.
Otherwise you can try to find a way to disable this linter, or ask yourself why not to meet all the dependency requirement.
It's best to think of the effect dependencies as "correct" or not, and not try to tailor them to achieve some specific behavior. (The vast majority of the time anyway)
This means that if an effect uses a value that could possibly change, then it's declared as a dependency. Sometimes you app works fine if your dependencies are "incorrect" because elsewhere you can guarantee a value is constant. But this is more about maintaining the application than having it work currently.
Later if you change how one of the dependencies works in a refactoring, then the effect now may need to re-run and doesn't leading to strange and hard to diagnose bugs like stale values where you can't tell where they come from.
If this leads to cumbersome hooks with huge dependency arrays that infinite loop themselves, then it's an indication that logic is messy and needs to be refactored, split into multiple effects, rethink how the data flows through your hooks, etc.
It's hard to advise specifically without seeing your code. But in your case it seems like you could make the "update function" take arguments instead, which means it could then be completely static. Or if you did use useCallback that depends on x,y then it would regenerate when those change, but you probably have a lot of logic to run when those change, so that's probably expected.
Summary:
I would advise you to take the warnings of eslint-plugin-react-hooks seriously, and clean your code until it passes. In the long wrong, in a large and complex application, it really helps keep things clean.
There are very rare exceptions that come up when doing non standard things, but it's worth it to try your best on this before resorting to ignoring those warnings.

How synchronize code when setState is called indirectly in React

I know that setState can be passed a callback to execute after the state is set. However I sometimes have code that I want to be executed in order where the state is set "indirectly" several layers down a method call.
For example:
this.makeDirty()
this.doThisAfter()
The makeDirty() call calls several methods, and one of them is responsible for calling another method that sets a dirty flag on the state. Because of this doThisAFter is called before state is set.
I understand that I could try to pass around callbacks all over the place to make sure they get into the setState callback argument, but this would significantly (and seemingly can be avoided) increase the complexity and ugliness of the code.
Is there a community-accepted solution for this? One thing I've thought of is instead of using setState I would always use a wrapper like mySetState that always calls the same callback method, one that looks for the presence of a queue of other functions that can be pre-filled. And then have some kind of API like:
doSyncronously( func1, func2, funcN...)
where the func2...N would be placed in a queue called by mySetState that is called by func1.
The problems with this are numerous, and I feel like I'll probably get it wrong. It also feels like I'm re-inventing the wheel or missing something.
Suggestions / comments?

Is using useEffect absolutely necessary?

I've been using React Hooks for a few months and have strictly adhered to using the useEffect hook as per the documentation.
A new colleague has joined the team and he is asking why is useEffect necessary. We've gone through the documentation together but he points out that implementing useEffect causes extra renders.
Here is a simple use case: A button is pressed to fetch some data. The click is handled by a Click event handler. He is wondering why he can't make the async call to the endpoint directly within the event handler.
I'm looking for an explanation that goes beyond "the docs say you shouldn't" and actually explains what the danger or downside of doing this is.
Might anyone be able to share why?
In short it's used for any side effects (not only fetching data):
A side effect is any application state change that is observable outside the called function other than its return value. Side effects include:
Modifying any external variable or object property (e.g., a global
variable, or a variable in the parent function scope chain)
Logging to the console
Writing to the screen
Writing to a file
Writing to the network
Triggering any external process
Calling any other functions with side-effects
Side effects are mostly avoided in functional programming, which makes the effects of a program much easier to understand, and much easier to test.
Haskell and other functional languages frequently isolate and encapsulate side effects from pure functions using monads.

What is the difference between seeding a action and call a 'setter' method of a store in reflux data flow?

What is the difference between seeding a action and call a 'setter' method of a store in reflux data flow?
TodoActions['add'](todo)
vs
TodoStore.add(todo)
Action will trigger your store via RefluxJS lib, but Store.Add() is calling add method directly
First off, it's useful to note that Whatever.func() and Whatever['func']() are just two different syntaxes for the same thing. So the only difference here in your example is what you're calling it on.
As far as calling a method in a store directly, vs. an action which then ends up calling that method in a store, the difference is architectural, and has to do with following a pattern that is more easily scaled, works more broadly, etc. etc.
If any given event within the program (such as, in this case, adding something) emits 1 clear action that anything can listen for, then it becomes MUCH easier to build large programs, edit previously made programs, etc. The component saying that this event has happened doesn't need to keep track of everywhere that might need to know about it...it just needs to say TodoActions.add(todo), and every other part of the program that needs to know about an addition happening can manage itself to make sure it's listening for that action.
So that's why we follow the 1 way looping pattern:
component -> action -> store -> back to component
Because then the flow of events happening is much more easily managed, because each part of the program can manage its own knowledge about the program state and when it needs to be changed. The component emitting the action doesn't need to know every possible part of the program that might need that action...it just needs to emit it.

Resources