Skip to content

Instantly share code, notes, and snippets.

@geraldodev
Created July 9, 2022 01:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geraldodev/8c7211b0645ab906fa2a8204674a4130 to your computer and use it in GitHub Desktop.
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
(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