Created
June 22, 2020 07:29
-
-
Save bradyclifford/063bbcfe022761510b0ef174200a0b01 to your computer and use it in GitHub Desktop.
React Context Provider
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
import React, { createContext, useContext, useState } from '~/session/react'; | |
import Session from 'sessionModule'; | |
import { resetSessionRequest } from 'session-client'; | |
const SessionContext = createContext(Session.default()); | |
SessionContext.displayName = 'Session'; | |
function useSession(initialSession) { | |
const [session, setSession] = useState(initialSession); | |
const resetSession = async (applicationId) => { | |
const response = await resetSessionRequest(applicationId); | |
if (response.isFailure) { | |
throw new TypeError('Unable to reset session'); | |
} | |
setSession(response); | |
} | |
return { | |
resetSession: resetSession, | |
session: session | |
} | |
} | |
export function SessionProvider({children, initialSession = Session.default()}) { | |
return ( | |
<SessionContext.Provider value={useSession(initialSession)}>{children}</SessionContext.Provider> | |
); | |
} | |
export default { | |
useSessionContext: () => useContext(SessionContext) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment