Created
July 9, 2022 01:35
-
-
Save geraldodev/8c7211b0645ab906fa2a8204674a4130 to your computer and use it in GitHub Desktop.
react-router use-fetcher hook "beanified" use-fetcher hook that encaspulate keeps you from using useLoaderData just for getting the result of the router load function
This file contains 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 crudis.ui.hooks.use-fetcher | |
(:require | |
["react-router-dom" :refer [useLoaderData useFetcher]] | |
[cljs-bean.core :refer [bean]] | |
)) | |
(defn use-fetcher | |
[] | |
(let [fetcher (useFetcher) | |
first-page (useLoaderData) | |
fetcher (bean fetcher)] | |
;; The :data attribute has the fresher data, but on the first render is js/undefined. | |
;; useLoaderData is the one who's returning the loader function result triggered by the route | |
;; So if we have :data we hand the fetcher as it is, if not we use useLoaderData | |
;; to avoid issuing an extra fetch because the data is already loaded but not visible | |
;; to fetcher | |
(if (:data fetcher) | |
fetcher | |
(assoc fetcher :data first-page)))) | |
(defn submit | |
[fetcher & args] | |
(apply (:submit fetcher) args)) | |
(defn load | |
[fetcher & args] | |
(apply (:load fetcher) args)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment