Fork me on GitHub
#reagent
<
2018-10-14
>
heyarne07:10:21

i'm experiencing some behavior i don't understand, maybe someone here can help. i have set up components like this:

(defn canvas [{:keys [draw] :as attrs}]
  (reagent/create-class
   {:component-did-update
    (fn [this]
      (let [canvas (reagent/dom-node this)
            width (.-offsetWidth canvas)
            height (.-offsetHeight canvas)
            ctx (.getContext canvas "2d")
            pixel-ratio (.-devicePixelRatio js/window)]
        (set! (. canvas -width) width)
        (set! (. canvas -height) height)
        ;; retina drawing code:
        ;; set up dimensions, reset the transform matrix to the identity
        ;; matrix and automatically scale up
        (when (> pixel-ratio 1)
          (set! (. canvas -width) (* pixel-ratio width))
          (set! (. canvas -height) (* pixel-ratio height))
          (set! (.. canvas -style -width) (str width "px"))
          (set! (.. canvas -style -height) (str height "px"))
          (.setTransform ctx 1 0 0 1 0 0)
          (.scale ctx pixel-ratio pixel-ratio))
        (draw ctx)))

    :reagent-render
    (fn []
      [:canvas.highres-canvas (dissoc attrs :draw)])}))

(defn draw-progress [ctx current-time duration]
  (println "draw-progress" current-time duration))

(defn current-progress [current-time duration]
  (println "current-progress" current-time duration)
  [canvas {:class-name "current-progress-canvas"
           :draw #(draw-progress % current-time duration)}])

heyarne07:10:23

now when current-progress gets new props, it prints them correctly, but draw-progress doesn't. as if i created a closure. i don't know where i should have done that though and how to avoid it

heyarne07:10:59

to be clear, draw-progress prints the same values over and over again, current-progress prints the updated ones.

heyarne09:10:22

ok, fixed this by passing the props of current-progress to canvas directly and then using (r/argv this) in did-update to extract them

juhoteperi09:10:30

@arne-clojurians The problem was that current-progress creates new function with #( ) each render and passes that to canvas but canvas destructures the draw fn only when the component is created, so component-did-update always calls the first fn

juhoteperi09:10:24

To access up to date draw property in component-did-update you should access it through (r/props this)

heyarne09:10:53

@juhoteperi aaaah true! thanks for the explanation