Last active
July 18, 2023 04:21
-
-
Save allensarkisyan/50cde019201c2739edda69a6dfc611cd to your computer and use it in GitHub Desktop.
Web5 - React Context Provider
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
/** | |
* @name Web5Provider | |
* @author Allen Sarkisyan | |
* @description Web5 - React Context Provider | |
* @copyright 2023 | |
* @license Open Source MIT License | |
*/ | |
import { createContext, useContext, useRef, useState, useEffect } from 'react'; | |
import { Web5 } from '@tbd54566975/web5'; | |
const Web5Context = createContext(); | |
export function Web5Provider({ | |
web5ConnectOptions = {}, | |
protocolDefinition = null, | |
children | |
}) { | |
const [isInitialized, setIsInitialized] = useState(false); | |
const web5Service = useRef(null); | |
useEffect(() => { | |
if (!isInitialized) { | |
Web5.connect(web5ConnectOptions).then(async (web5ConnectResponse) => { | |
const { web5, did } = web5ConnectResponse; | |
if (protocolDefinition && protocolDefinition !== null) { | |
const { status, protocol } = await web5.dwn.protocols.configure({ | |
message: { definition: protocolDefinition } | |
}); | |
console.log('web5-protocol-init', { did, status, protocol }); | |
} | |
web5Service.current = web5ConnectResponse; | |
}); | |
setIsInitialized(true); | |
} | |
}, [isInitialized, web5ConnectOptions, protocolDefinition]); | |
return ( | |
<Web5Context.Provider value={web5Service.current}> | |
{children} | |
</Web5Context.Provider> | |
); | |
} | |
export function useWeb5() { | |
return useContext(Web5Context); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example Web5Provider use
Example useWeb5 hook use