@substrate/react-context
TypeScript icon, indicating that this package has built-in type declarations

0.7.2 • Public • Published

Available Scripts

This repo contains a set of utilities provided as react context.

Usage example

With Polkadot-js api

in your App.jsx (or App.tsx)

import { ApiPromiseContextProvider } from '@substrate/react-context';

const WS_PROVIDER = process.env.REACT_APP_WS_PROVIDER;

const App = () => {

	if (!WS_PROVIDER) {
		console.error('REACT_APP_WS_PROVIDER not set');
		return null;
	}

	const provider = new WsProvider(WS_PROVIDER);

	return (
		<ApiPromiseContextProvider provider={provider}>
			<MainApp />      
		</ApiPromiseContextProvider>
	);
};

Then you can access the api anywhere in your app using the hook useContext(ApiPromiseContext):

import { ApiPromiseContext } from '@substrate/react-context';

export default function ()  {
		// get the api and the isApiReady flag
		const { api, isApiReady } = useContext(ApiPromiseContext);

	useEffect(() => {
		// return early if the api is not ready
		if (!isApiReady) {
			return;
		}

		let unsubscribe: () => void;

		// use the api
		api.derive.chain.bestNumber((number) => {
			setCurrentBlock(number);
		})
			.then(unsub => {unsubscribe = unsub;})
			.catch(e => console.error(e));

		return () => unsubscribe && unsubscribe();
	}, [api, isApiReady]);
}

Package Sidebar

Install

npm i @substrate/react-context

Weekly Downloads

4

Version

0.7.2

License

Apache-2.0

Unpacked Size

94.8 kB

Total Files

52

Last publish

Collaborators

  • ryan-parity
  • paritytech
  • tarikgul
  • marshacb
  • imod7
  • alexandru.vasile
  • jimmychu0807
  • paritytech-ci
  • andreieres
  • jacogr
  • kianenigma
  • joepetrowski
  • jeluard
  • wirednkod
  • niklasad1
  • jsdw