Fork me on GitHub
#clojurescript
<
2024-01-13
>
Christian Dean12:01:00

I have a ‘like’ function that lets a user like a piece of content so I can display a likes count under it publicly. The function first resets a bunch of atoms with the current like count, user ID, and other stuff before calling the database merge function to merge the user ID into the likes count. The problem is that the function doesn’t work on the first click, but works on the 2nd click. I guess this is bc merge is called before the atoms have been set. What’s the best way to have the merge function wait until all atoms are set? Currently I just call the whole function once, and then again after a js.setTimeout of 300. But apparently this can be problematic.

p-himik12:01:31

Not enough details to give a good answer, and I don't know what to ask for since it's all rather vague. But I can take a look if you create an MRE.

p-himik12:01:30

If by "merge" you meant that merge-in-doc, then it cannot happen before the atoms are reset. reset! is not async. Something else must be the cause. How do you determine that it doesn't work on the first click? The data is not in the Firebase instance? The UI is not updated somewhere? Something else?

Christian Dean12:01:10

It doesn’t register in the firebase emulator document until I click ‘like’ twice

p-himik12:01:55

It's not about the merge at all, it's probably about the order of operations on atoms - derefs and resets. You really should reconsider that approach of storing the state in a multitude of disparate atoms, that's just asking for a headache - like this one. You're getting current-likes just to create updated-likes that you then store in Firebase. But you don't use updated-likes to set the value of story-likes*, instead you're using the old value. If you don't want to get rid of the multitude of atoms, at least consider storing related bits of data in a map in a single atom and then use swap! instead of reset!. It would be much, much easier to reason about.

Christian Dean12:01:37

Ah, you’re right. Putting all the atoms into one story-state atom solved it. Thank you

👍 1