Search code examples
clojurereagent

Reagent atom swap! change state to all values from keys


We have an atom with some keys and boolean values:

(def btns (reagent.core/atom {:a true :b true :c true}))

I need to change the state of all keys, like this: {:a false :b false :c false}

I tried this, but not good solution, and not working:

   (for [btn @btns]
        (swap! btns assoc (key btn) false))

Solution

  • you can update multiple keys this way:

    user> (def a (atom {:a true :b true :c true}))
    ;;=> #<Atom@af0fa6a: {:a true, :b true, :c true}>
    
    user> (swap! a into {:b false :c false})
    ;;=> {:a true, :b false, :c false}
    

    or like this:

    user> (swap! a assoc :a false :c false)
    ;;=> {:a false, :b true, :c false}
    

    if you want to update all the keys in atom to false it could also look like this:

    user> (reset! a (zipmap (keys @a) (repeat false)))
    ;;=> {:a false, :b false, :c false}
    

    or like this:

    user> (swap! a #(zipmap (keys %) (repeat false)))
    ;;=> {:a false, :b false, :c false}
    

    update

    also, it is good to abstract out the util function, to make it more readable:

    (defn assoc-all-keys [data val]
      (zipmap (keys data) (repeat val)))
    
    user> (swap! a assoc-all-keys false)
    ;;=> {:a false, :b false, :c false}