Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Introduce pure clojure wrappers for React Context #594

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

ingesolvoll
Copy link

@ingesolvoll ingesolvoll commented Aug 9, 2023

This PR suggests a pure Clojure API for React Context. It's a very simple wrapper around Provider and Consumer. It does not convert the context value in any way.

If the Reagent maintainers decide that this abstraction is useful and within relevant scope, I will complete this PR with tests, docs, and any other things missing in order to be considered for merge.

A short code example:

(require '[reagent.context :as r.context])

(def my-context (r.context/make-context "my-context" "default"))

[r.context/provider {:value {:foo :bar} ;; The value here can be anything, does not need to be a map
                     :context my-context}
    [r.context/consumer {:context my-context}
     (fn [{:keys [foo]}]
       [:div ":foo is a keyword: " (pr-str foo)])]

    ;; The `with-context` macro cuts away some boilerplate from the above
    (r.context/with-context [{:keys [foo]} my-context]
      [:div "From the macro: " (pr-str foo)])]

The code in this PR was written by the developers at Whimsical

Comment on lines +38 to +41
(let [value (.-context (r/current-component))]
(when (undefined? value)
(throw (js/Error. (str "Missing provider for " (.-displayName context)))))
(render-f value)))]

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

one of the problems with using the Consumer component is that you couldn't deref ratoms safely inside the render fn; they wouldn't setup a listener because they wouldn't have the reactive context. Does this fix that?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants