Created
February 18, 2022 18:42
-
-
Save ynonp/57c429315d282a82b145a0b94db92cb7 to your computer and use it in GitHub Desktop.
ClojureScript useEffect example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns reagent-useeffect-demo.core | |
(:require | |
[reagent.core :as r] | |
[react :as react] | |
[cljs.core.async :refer [go]] | |
[cljs.core.async.interop :refer-macros [<p!]] | |
[reagent.dom :as rdom])) | |
(defn use-pokemon [id] | |
(let [[data set-data] (react/useState {}) | |
active? (r/atom true)] | |
(react/useEffect (fn [] | |
(go | |
(let [response (<p! (js/fetch | |
(str "https://pokeapi.co/api/v2/pokemon/" id))) | |
data (<p! (.json response))] | |
(if @active? (set-data data)))) | |
(fn [] | |
(reset! active? false))) | |
(array id)) | |
data)) | |
(defn pokemon [id] | |
(let [ | |
data (use-pokemon id) | |
] | |
[:div | |
[:p "ID: " (.stringify js/JSON id)] | |
[:p "Name " (aget data "name")]])) | |
(defn home-page [] | |
(r/with-let [ | |
id (r/atom (inc (rand-int 10))) | |
] | |
[:span.main | |
[:f> pokemon @id] | |
[:button { :on-click #(reset! id (inc (rand-int 10))) } "New ID"] | |
[:p "Welcome to reagent useeffect demo"]])) | |
(defn init! [] | |
(rdom/render [:f> home-page] (.getElementById js/document "app"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This example is part of my React course. To learn more please visit:
https://www.tocode.co.il