Skip to content

Instantly share code, notes, and snippets.

@allensarkisyan
Last active July 18, 2023 04:21
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 allensarkisyan/50cde019201c2739edda69a6dfc611cd to your computer and use it in GitHub Desktop.
Save allensarkisyan/50cde019201c2739edda69a6dfc611cd to your computer and use it in GitHub Desktop.
Web5 - React Context Provider
/**
* @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);
}
@allensarkisyan
Copy link
Author

Example Web5Provider use

import { Web5Provider } from './Web5Provider';
import protocolDefinition from './YOUR_PROTOCOL_DEFINITION.json';
import App from './App';

function Root() {
  return (
    <Web5Provider protocolDefinition={protocolDefinition}>
      <App />
    </Web5Provider>
  )
}

Example useWeb5 hook use

import { useWeb5 } from './Web5Provider';

function App() {
  const { web5, did } = useWeb5();
  return null;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment