@lifi/widget
Version:
LI.FI Widget for cross-chain bridging and swapping. It will drive your multi-chain strategy and attract new users from everywhere.
50 lines (49 loc) • 2.02 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useContext, useEffect, useRef } from 'react';
import { useFormContext } from 'react-hook-form';
import { useChains } from '../../hooks';
import { FormKey } from '../../providers';
import { createChainOrderStore } from './createChainOrderStore';
export const ChainOrderStoreContext = createContext(null);
export function ChainOrderStoreProvider({ children, ...props }) {
const storeRef = useRef();
const { chains: filteredChains } = useChains();
const { setValue, getValues } = useFormContext();
if (!storeRef.current) {
storeRef.current = createChainOrderStore(props);
}
useEffect(() => {
if (filteredChains) {
const chainOrder = storeRef.current
?.getState()
.initializeChains(filteredChains.map((chain) => chain.id));
if (chainOrder) {
const [fromChainValue, toChainValue] = getValues([
FormKey.FromChain,
FormKey.ToChain,
]);
if (!fromChainValue) {
setValue(FormKey.FromChain, chainOrder[0]);
}
if (!toChainValue) {
setValue(FormKey.ToChain, chainOrder[0]);
}
}
}
}, [filteredChains, getValues, setValue]);
return (_jsx(ChainOrderStoreContext.Provider, { value: storeRef.current, children: children }));
}
export function useChainOrderStore(selector, equalityFn) {
const useStore = useContext(ChainOrderStoreContext);
if (!useStore) {
throw new Error(`You forgot to wrap your component in <${ChainOrderStoreProvider.name}>.`);
}
return useStore(selector, equalityFn);
}
export function useChainOrderStoreContext() {
const useStore = useContext(ChainOrderStoreContext);
if (!useStore) {
throw new Error(`You forgot to wrap your component in <${ChainOrderStoreProvider.name}>.`);
}
return useStore;
}