Skip to content

Instantly share code, notes, and snippets.

@JordanMarr
Last active June 18, 2020 07:39
Show Gist options
  • Save JordanMarr/fe4474bb4fedab4c0adc3895d60610ff to your computer and use it in GitHub Desktop.
Save JordanMarr/fe4474bb4fedab4c0adc3895d60610ff to your computer and use it in GitHub Desktop.
Fable React Context
module App
open Feliz
open Fable.React
open Fable.React.Props
open Fable.UIFabric
open Auth
open HookRouter
open Contexts
let app = React.functionComponent(fun () ->
let authResult, logout = useAuth()
let isPM, email = match authResult with | Authenticated (user, token) -> user.IsPM, user.Email | _ -> false, ""
let routes = {|
``/`` = fun _ -> SplashPage.page()
``/timesheet-daily`` = fun _ -> TimesheetPage.page { Type = Daily }
``/timesheet-weekly`` = fun _ -> TimesheetPage.page { Type = Weekly }
``/projects`` = fun _ -> ProjectsPage.page()
``/project-create`` = fun _ -> ProjectEditPage.page {| projectId = "" |}
``/project-edit/:projectId`` = fun p -> ProjectEditPage.page p
``/rolling-schedule/:projectId`` = fun p -> RollingSchedulePage.page p
``/users`` = fun _ -> UsersPage.page()
|}
let content = HookRouter.useRoutes routes |> Option.defaultValue (h1[] [str "Not Found"])
div [] [
div [Class "p-3"] [
match authResult with
| Authenticating ->
Stack.stack [Stack.Gap 20; Stack.Horizontal] [
Spinner.spinner [Spinner.Size Spinner.SpinnerSize.Large] []
b [] [str "Authenticating..."]
]
| Denied reason ->
div [Class"alert alert-danger"] [
h4 [] [str "Unable to Login"]
p [] [ str reason ]
]
| Authenticated (user, token) ->
// Wrap content with a context provider
React.contextProvider(Contexts.appContext, { User = user; Token = token },
content
)
]
]
)
module Contexts
open Feliz
open Elmish
type AppState = {
User: User
Token: string
}
let private init = { User = { Username = ""; Email = ""; IsPM = false; IsAdmin = false; IsEnabled = true }; Token = "" }
let appContext = React.createContext<AppState>(name = "AppContext", defaultValue = init)
module SplashPage
open System
open Feliz
open Fable.React
open Fable.React.Props
open Fable.UIFabric
let page = React.functionComponent(fun () ->
let ctx = React.useContext(Contexts.appContext)
if ctx.User.IsAdmin then
div [] [ str "Logged in as Admin" ]
else
div [] [ str "Logged in as User" ]
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment