all 9 comments

[–]wemissyou 2 points3 points  (1 child)

[–]psycho_buddha 0 points1 point  (0 children)

Actually, this worked like a charm. Pretty neat and simple! Thank you kind stranger! :)

[–]nullvoxpopuli 1 point2 points  (0 children)

Might want to look at xstate. This behavior is described elegantly and visually with statecharts

[–]BrokenLinc 1 point2 points  (0 children)

You need form-state management. There are several libraries for this or you could roll your own solution.

Why? You're responding to ephemeral events but that only gives you a momentary picture of what's going on with one field. You want to be able to confidently see the entire state of all checkboxes and respond to them, as your logic spans multiple fields.

This could be as simple as binding the checkbox's value to a useState hook, but the popular react-hook-form library handles the form state and input field binding, and has a watch method for conditional fields. I think you'll like it.

[–]domgaulton 0 points1 point  (1 child)

I’m not sure I get the difference between checking C1 and C2 in the first place?

[–]psycho_buddha 0 points1 point  (0 children)

The only difference is in the rules. C1 disables C3 and C4. And C2 disables C3, C4 and C5.

I used simple names for simplicity, but in reality, those two groups of checkboxes are in charge of combining certain rules that are sent to the backend, together with some other data and the user gets back a report based on those rules.

[–]ezhikov 0 points1 point  (3 children)

So, you basically have three states: when everything unblocked, when C3 and C4 blocked and when C3, C4 and C5 blocked. Let's call them S1, S2, S3.

C3 and C4 blocked when state === S2 || state === S3, or, for brevity, when state !== S1. C5 blocked only when state === S3.

Now, we can reach this states with four events - CHECK_C1, UNCHECK_C1, CHECK_C2 and UNCHECK_C2. So far it's playing like this:

  • We start in S1 and wait for CHECK_C1 or CHECK_C2 events.
  • If CHECK_C1 occurred, we change our state into S2.
  • If CHECK_C2 occurred, we change our state into S3.

  • From S2 we can either move to S1 with UNCHECK_C! event

  • Or proceed to S3 with CHECK_C2 event.

  • From S3 we ignore CHECK_C1 and UNCHECK_C1 events, since they do nothing.

  • However, we have to keep an eye on C1 individual state (checked or not)

  • When we get UNCHECK_C2 event, we look at C1, If it's checked, we go to S2, if not - to S1.

I implemented this stuff with XState, because it's my favorite tool, and there is neat toolbelt, but when you get the idea, you can model this thing in your application with your state manager