react#useCallback JavaScript Examples
The following examples show how to use
react#useCallback.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: use-resize-observer.js From MDXP with MIT License | 6 votes |
useResizeObserver = () => {
const [observerEntry, setObserverEntry] = useState([undefined, undefined]);
const [node, setNode] = useState(null);
const observer = useRef(null);
const disconnect = useCallback(() => observer.current?.disconnect(), []);
const observe = useCallback(() => {
observer.current = new ResizeObserver(([entry]) => {
setObserverEntry([entry.contentRect.width, entry.contentRect.height]);
});
if (node) {
observer.current.observe(node);
}
}, [node]);
useLayoutEffect(() => {
observe();
return () => disconnect();
}, [disconnect, observe]);
return [setNode, ...observerEntry];
}
Example #2
Source File: Application.js From about-1hive with GNU General Public License v3.0 | 6 votes |
export default function Provider({ children }) {
const [state, dispatch] = useReducer(reducer, INITIAL_STATE)
const updateDarkMode = useCallback(mode => {
dispatch({
type: UPDATE_DARKMODE,
payload: {
mode
}
})
}, [])
return (
<ApplicationContext.Provider value={useMemo(() => [state, { updateDarkMode }], [state, updateDarkMode])}>
{children}
</ApplicationContext.Provider>
)
}
Example #3
Source File: app-logic.js From payroll-app with GNU Affero General Public License v3.0 | 6 votes |
export function useRequestMode(requestPanelOpen) {
const [requestMode, setRequestMode] = useState({
mode: MODE.ADD_EMPLOYEE,
data: null,
})
const updateMode = useCallback(
newMode => {
setRequestMode(newMode)
requestPanelOpen()
},
[requestPanelOpen]
)
return [requestMode, updateMode]
}
Example #4
Source File: useCopyToClipboard.js From tulip-frontend with GNU Affero General Public License v3.0 | 6 votes |
export function useCopyToClipboard() {
const toast = useToast()
return useCallback(
(text, confirmationMessage = 'Copied') => {
copy(text)
if (confirmationMessage) {
toast(confirmationMessage)
}
},
[toast]
)
}
Example #5
Source File: Allowances.js From uniswap-v1-frontend with GNU General Public License v3.0 | 6 votes |
export default function Provider({ children }) {
const [state, dispatch] = useReducer(reducer, {})
const update = useCallback((networkId, address, tokenAddress, spenderAddress, value, blockNumber) => {
dispatch({ type: UPDATE, payload: { networkId, address, tokenAddress, spenderAddress, value, blockNumber } })
}, [])
return (
<AllowancesContext.Provider value={useMemo(() => [state, { update }], [state, update])}>
{children}
</AllowancesContext.Provider>
)
}
Example #6
Source File: _Helpers.js From acy-dex-interface with MIT License | 6 votes |
export function useLocalStorageByChainId(chainId, key, defaultValue) {
const [internalValue, setInternalValue] = useLocalStorage(key, {});
const setValue = useCallback(
value => {
setInternalValue(internalValue => {
if (typeof value === "function") {
value = value(internalValue[chainId] || defaultValue);
}
const newInternalValue = {
...internalValue,
[chainId]: value
};
return newInternalValue;
});
},
[chainId, setInternalValue, defaultValue]
);
let value;
if (chainId in internalValue) {
value = internalValue[chainId];
} else {
value = defaultValue;
}
return [value, setValue];
}
Example #7
Source File: useThrottle.js From akashlytics-deploy with GNU General Public License v3.0 | 6 votes |
useThrottledCallback = (effect, deps, delay) => {
// eslint-disable-next-line react-hooks/exhaustive-deps
return useCallback(
throttle(() => {
effect();
}, delay),
[...(deps || []), delay]
);
}
Example #8
Source File: ThemeProvider.js From tisn.app with GNU Affero General Public License v3.0 | 6 votes |
ThemeProvider = ({ children }) => {
const prefersDarkMode = useMediaQuery('@media (prefers-color-scheme: dark)');
const preferredThemeType = prefersDarkMode ? 'dark' : 'light';
const [themeType, setThemeType] = useState(
storedThemeType || preferredThemeType
);
const toggleTheme = useCallback(() => {
setThemeType((themeType) => (themeType === 'light' ? 'dark' : 'light'));
}, []);
useEffect(() => {
localStorage.setItem('themeType', themeType);
const themeMetaTag = document.querySelector('meta[name="theme-color"]');
if (themeMetaTag) {
themeMetaTag.setAttribute(
'content',
themeType === 'dark' ? grey[800] : indigo[500]
);
}
}, [themeType]);
return (
<MuiThemeProvider theme={themes[themeType]}>
<ToggleThemeContext.Provider value={toggleTheme}>
{children}
</ToggleThemeContext.Provider>
</MuiThemeProvider>
);
}
Example #9
Source File: hooks.js From react-firechat with MIT License | 6 votes |
export function useMedia(queries, values, defaultValue) {
// Array containing a media query list for each query
const mediaQueryLists = queries.map(q => window.matchMedia(q));
// Function that gets value based on matching media query
const getValue = useCallback(() => {
// Get index of first media query that matches
const index = mediaQueryLists.findIndex(mql => mql.matches);
// Return related value or defaultValue if none
return typeof values[index] !== 'undefined' ? values[index] : defaultValue;
}, [mediaQueryLists, values, defaultValue]);
// State and setter for matched value
const [value, setValue] = useState(getValue);
useEffect(() => {
// Event listener callback
// Note: By defining getValue outside of useEffect we ensure that it has ...
// ... current values of hook args (as this hook callback is created once on mount).
const handler = () => setValue(getValue);
// Set a listener for each media query with above handler as callback.
mediaQueryLists.forEach(mql => mql.addListener(handler));
// Remove listeners on cleanup
return () => mediaQueryLists.forEach(mql => mql.removeListener(handler));
}, [getValue, mediaQueryLists]);
return value;
}
Example #10
Source File: hooks.js From react-trello with MIT License | 6 votes |
export function useClickOutsideEffect(node, onClickOutside) {
const handleClick = useCallback((e) => {
if (!node?.current?.contains(e.target) && typeof(onClickOutside) === "function") {
onClickOutside();
}
}, [node, onClickOutside]);
useEffect(() => {
document.addEventListener('mousedown', handleClick);
return () => {
document.removeEventListener('mousedown', handleClick);
};
}, [handleClick]);
}
Example #11
Source File: index.js From NFT-Marketplace with MIT License | 6 votes |
DropZone = ({ onFileUploaded }) => {
const classes = useStyles();
const [selectedFileUrl, setSelectedFileUrl] = useState('');
const onDrop = useCallback(acceptedFiles => {
const file = acceptedFiles[0];
const fileUrl = URL.createObjectURL(file);
setSelectedFileUrl(fileUrl);
onFileUploaded(file);
}, [onFileUploaded]);
const { getRootProps, getInputProps } = useDropzone({
onDrop,
accept: 'image/*'
});
return (
<div className={classes.dropzone} {...getRootProps()}>
<input {...getInputProps()} accept='image/*' />
{ selectedFileUrl
? <img src={selectedFileUrl} alt="Point thumbnail"/>
: (
<p>
<CloudUploadIcon />
NFT image
</p>
)
}
</div>
);
}
Example #12
Source File: UsersFilter.js From ponce-tournois-mario-kart with MIT License | 6 votes |
function UsersFilter({ usernameFilter, setUsernameFilter }) {
const [username, setUsername] = useState(usernameFilter);
const debounceFilter = useCallback(
_.debounce((f) => setUsernameFilter(f), 300),
[]
);
return (
<input
className="users__filter"
placeholder="Rechercher par nom d'utilisateur"
value={username}
onChange={(e) => {
setUsername(e.target.value);
debounceFilter(e.target.value);
}}
/>
);
}
Example #13
Source File: MsgDetailSectionHeaderContainer.js From airdnd-frontend with MIT License | 6 votes |
MsgDetailSectionHeaderContainer = () => {
// ! redux
const dispatch = useDispatch();
// ! event
const onCloseSection = useCallback(() => {
return dispatch(hideMsgDetailSection());
}, [dispatch]);
return <MsgDetailSectionHeader onCloseSection={onCloseSection} />;
}
Example #14
Source File: BreadcrumbMenu.js From beautiful-react-ui with MIT License | 6 votes |
BreadcrumbMenu = (props) => {
const { items } = props;
const [shown, setIsShown] = useState(false);
const Trigger = (
<Button icon="ellipsis-v" color="transparent" outline size="small" className="bi-breadcrumbs-menu-button" />
);
const onToggleHandler = useCallback(() => {
setIsShown(!shown);
}, [shown]);
return (
<li className="bi breadcrumb-item breadcrumb-menu">
<DropDown trigger={Trigger} isShown={shown} onToggle={onToggleHandler} placement="bottom-left">
{items.map((item) => {
if (item.render) {
return item.render();
}
return <DropDown.Link href={item.path} icon={item.icon}>{item.label}</DropDown.Link>;
})}
</DropDown>
</li>
);
}
Example #15
Source File: SettingAccordion.js From Website with MIT License | 6 votes |
SettingAccordion = props => {
const [openItem, setOpenItem] = useState();
const clickHandler = useCallback(key => {
setOpenItem(prev => {
if (key === prev) {
return "";
} else {
return key;
}
});
}, []);
return (
<div style={{ width: "100%" }}>
{Children.map(props.children, Element =>
cloneElement(Element, {
onClick: clickHandler,
open: Element.props?.name === openItem,
})
)}
</div>
);
}
Example #16
Source File: useClickOutside.js From eos-icons-landing with MIT License | 6 votes |
useClickOutside = (ref, callback) => {
const handleClick = useCallback(
(event) => {
if (ref.current && !ref.current.contains(event.target)) {
callback()
}
},
[callback, ref]
)
useEffect(() => {
document.addEventListener('click', handleClick)
return () => {
document.removeEventListener('click', handleClick)
}
}, [handleClick])
}
Example #17
Source File: sc.interaction.js From Artion-Client with GNU General Public License v3.0 | 6 votes |
useContract = () => {
const { chainId } = useWeb3React();
const loadContract = useCallback(
async (address, abi) => {
const provider = new ethers.providers.Web3Provider(window.ethereum);
const signer = provider.getSigner();
return new ethers.Contract(address, abi, signer);
},
[chainId]
);
const getAccountBalance = useCallback(
async address => {
const provider = new ethers.providers.Web3Provider(window.ethereum);
let balance = await provider.getBalance(address);
balance = ethers.utils.formatEther(balance);
return balance;
},
[chainId]
);
return { loadContract, getAccountBalance };
}
Example #18
Source File: Modals.js From filen-mobile with GNU Affero General Public License v3.0 | 6 votes |
FullscreenLoadingModal = memo(() => {
const fullscreenLoadingModalVisible = useStore(useCallback(state => state.fullscreenLoadingModalVisible))
const setFullscreenLoadingModalVisible = useStore(useCallback(state => state.setFullscreenLoadingModalVisible))
const setFullscreenLoadingModalDismissable = useStore(useCallback(state => state.setFullscreenLoadingModalDismissable))
const fullscreenLoadingModalDismissable = useStore(useCallback(state => state.fullscreenLoadingModalDismissable))
if(!fullscreenLoadingModalVisible){
return null
}
return (
<Pressable style={{
position: "absolute",
height: "100%",
width: "100%",
backgroundColor: "rgba(0, 0, 0, 0.4)",
justifyContent: "center",
alignItems: "center"
}} onPress={() => {
if(fullscreenLoadingModalDismissable){
setFullscreenLoadingModalVisible(false)
setFullscreenLoadingModalDismissable(false)
}
}}>
<ActivityIndicator size={"small"} color="white" />
</Pressable>
)
})
Example #19
Source File: menu.js From about-1hive with GNU General Public License v3.0 | 5 votes |
export function useToggle(initialState = false) {
const [state, setState] = useState(initialState)
const toggle = useCallback(() => setState(state => !state), [])
return [state, toggle]
}
Example #20
Source File: App.js From payroll-app with GNU Affero General Public License v3.0 | 5 votes |
function App() {
const [screen, setScreen] = useState(MY_PAYROLL.id)
const {
actions,
isSyncing,
requestMode,
panelState,
requests,
} = useAppLogic()
const { appearance } = useGuiStyle()
const { layoutName } = useLayout()
const compactMode = layoutName === 'small'
const handleScreenChange = useCallback(screenId => {
setScreen(SCREENS[screenId].id)
}, [])
return (
<Main theme={appearance} assetsUrl="./aragon-ui">
<SyncIndicator visible={isSyncing} />
<Header
primary="Payroll"
secondary={
!isSyncing && (
<>
{screen === MY_PAYROLL.id && (
<Button
mode="strong"
onClick={requests.payday}
label="Request salary"
icon={<IconPlus />}
display={compactMode ? 'icon' : 'label'}
/>
)}
{screen === TEAM_PAYROLL.id && (
<Button
mode="strong"
onClick={requests.addEmployee}
label="New employee"
icon={<IconPlus />}
display={compactMode ? 'icon' : 'label'}
/>
)}
</>
)
}
/>
{
<Tabs
items={SCREENS.map(screen => screen.label)}
selected={SCREENS.findIndex(s => s.id === screen)}
onChange={handleScreenChange}
/>
}
{screen === MY_PAYROLL.id && <MyPayroll isSyncing={isSyncing} />}
{screen === TEAM_PAYROLL.id && (
<TeamPayroll
isSyncing={isSyncing}
onRequestEditEquityOption={requests.editEquityOption}
onRequestTerminateEmployee={requests.terminateEmployee}
/>
)}
<Panel
requestMode={requestMode}
panelState={panelState}
actions={actions}
/>
</Main>
)
}
Example #21
Source File: ScreenProviders.js From tulip-frontend with GNU Affero General Public License v3.0 | 5 votes |
function ProviderButton({ id, provider, onActivate }) {
const theme = useTheme()
const handleClick = useCallback(() => {
onActivate(id)
}, [onActivate, id])
return (
<ButtonBase
key={id}
onClick={handleClick}
css={`
position: relative;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
height: ${12 * GU}px;
background: ${theme.surface};
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.15);
border-radius: ${RADIUS}px;
&:active {
top: 1px;
box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);
}
`}
>
<img src={provider.image} alt="" height={5.25 * GU} />
<div
css={`
margin-top: ${1 * GU}px;
${textStyle('body1')};
`}
>
{provider.name}
</div>
</ButtonBase>
)
}
Example #22
Source File: ModeSelector.js From uniswap-v1-frontend with GNU General Public License v3.0 | 5 votes |
function ModeSelector({ location: { pathname }, history }) {
const { t } = useTranslation()
const [modalIsOpen, setModalIsOpen] = useState(false)
const activeTabKey = poolTabOrder[poolTabOrder.findIndex(({ regex }) => pathname.match(regex))].textKey
const navigate = useCallback(
direction => {
const tabIndex = poolTabOrder.findIndex(({ regex }) => pathname.match(regex))
history.push(poolTabOrder[(tabIndex + poolTabOrder.length + direction) % poolTabOrder.length].path)
},
[pathname, history]
)
const navigateRight = useCallback(() => {
navigate(1)
}, [navigate])
const navigateLeft = useCallback(() => {
navigate(-1)
}, [navigate])
useBodyKeyDown('ArrowDown', navigateRight, modalIsOpen)
useBodyKeyDown('ArrowUp', navigateLeft, modalIsOpen)
return (
<OversizedPanel hideTop>
<LiquidityContainer
onClick={() => {
setModalIsOpen(true)
}}
>
<LiquidityLabel>{t(activeTabKey)}</LiquidityLabel>
<ColoredDropdown alt="arrow down" />
</LiquidityContainer>
<Modal
isOpen={modalIsOpen}
maxHeight={50}
onDismiss={() => {
setModalIsOpen(false)
}}
>
<PoolModal>
{poolTabOrder.map(({ path, textKey, regex }) => (
<StyledNavLink
key={path}
to={path}
isActive={(_, { pathname }) => pathname.match(regex)}
onClick={() => {
setModalIsOpen(false)
}}
>
{t(textKey)}
</StyledNavLink>
))}
</PoolModal>
</Modal>
</OversizedPanel>
)
}
Example #23
Source File: index.js From acy-dex-interface with MIT License | 5 votes |
useConnectWallet=()=> {
const { activate, deactivate } = useWeb3React();
const connectWalletByLocalStorage = useCallback(
() => {
const walletName = localStorage.getItem("wallet");
const login_status = localStorage.getItem("login_status");
console.log('ymj', walletName, login_status);
if (login_status == 'off'){
return;
}
if (walletName === 'metamask' || walletName === 'opera' || walletName === 'bitkeep') {
activate(injected);
} else if (walletName === 'walletconnect') {
activate(walletconnect);
} else if (walletName === 'coinbase') {
activate(walletlink);
} else if (walletName === 'fortmatic') {
activate(fortmatic);
} else if (walletName === 'portis') {
activate(portis);
} else if (walletName === 'torus') {
activate(torus);
} else if (walletName === 'trezor') {
activate(trezor);
} else if (walletName === 'ledger') {
activate(ledger);
} else if (walletName === 'binance') {
activate(binance);
} else if (walletName === 'nabox') {
activate(nabox);
}
else {
console.log("wallet ERROR");
activate(injected);
}
localStorage.setItem("login_status", "on")
},
[activate],
)
return connectWalletByLocalStorage;
}
Example #24
Source File: index.js From ActiveLearningStudio-react-client with GNU Affero General Public License v3.0 | 5 votes |
// TODO: need to clean up attribute
function DeletePopup(props) {
const {
ui,
selectedProject,
hideDeletePopup,
deleteProject,
deletePlaylist,
deleteResource,
} = props;
// remove popup when escape is pressed
const escFunction = useCallback((event) => {
if (event.keyCode === 27) {
hideDeletePopup(event);
}
}, [hideDeletePopup]);
useEffect(() => {
document.addEventListener('keydown', escFunction, false);
return () => {
document.removeEventListener('keydown', escFunction, false);
};
}, [escFunction]);
const deleteEntity = useCallback((deleteType, id) => () => {
if (deleteType === 'Project') {
deleteProject(id);
} else if (deleteType === 'Playlist') {
deletePlaylist(selectedProject.id, id);
} else if (deleteType === 'Activity') {
deleteResource(id);
}
}, [selectedProject, deleteProject, deletePlaylist, deleteResource]);
return (
<FadeDiv className="popup">
<div className="modal fade" role="dialog" aria-hidden="true">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-body">
<h5>{`Delete "${ui.title}"?`}</h5>
<p>
{`You're about to permanently delete this ${ui.deleteType} and all of its data.`}
</p>
<p>Do you want to continue?</p>
</div>
<div className="modal-footer">
<button
type="submit"
className="btn btn-sm btn-danger"
onClick={deleteEntity(ui.deleteType, ui.id)}
>
Delete
</button>
<button
type="button"
className="btn btn-sm btn-default"
data-dismiss="modal"
onClick={hideDeletePopup}
>
Cancel
</button>
</div>
</div>
</div>
</div>
</FadeDiv>
);
}
Example #25
Source File: PricePoviderContext.js From akashlytics-deploy with GNU General Public License v3.0 | 5 votes |
PriceProvider = ({ children }) => {
const [priceData, setPriceData] = useState({});
const [isLoadingPriceData, setIsLoadingPriceData] = useState(false);
const loadPriceData = useCallback(async () => {
if (isLoadingPriceData) return;
setIsLoadingPriceData(true);
try {
const endpointUrl = "https://api.coingecko.com/api/v3/coins/akash-network";
// console.log("Fetching latest market data from " + endpointUrl);
const response = await axios.get(endpointUrl);
const data = response.data;
const aktMarketData = {
price: parseFloat(data.market_data.current_price.usd),
volume: parseInt(data.market_data.total_volume.usd),
marketCap: parseInt(data.market_data.market_cap.usd),
marketCapRank: data.market_cap_rank,
priceChange24h: parseFloat(data.market_data.price_change_24h),
priceChangePercentage24: parseFloat(data.market_data.price_change_percentage_24h)
};
setPriceData(aktMarketData);
} catch (error) {
console.log(error);
setIsLoadingPriceData(false);
}
}, [isLoadingPriceData]);
useEffect(() => {
loadPriceData();
const priceDataIntervalId = setInterval(async () => {
await loadPriceData();
}, 300_000); // refresh every 5 min
return () => {
clearInterval(priceDataIntervalId);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return <PriceProviderContext.Provider value={{ priceData, isLoadingPriceData, loadPriceData }}>{children}</PriceProviderContext.Provider>;
}
Example #26
Source File: api.js From vpp with MIT License | 5 votes |
export function ApiProvider(props) {
const [api, setApi] = useState(initialApi);
const [apiState, setApiState] = useState('');
useEffect(() => {
try {
(async () => {
const wsProvider = new WsProvider(ENDPOINT);
const a = await ApiPromise.create({ provider: wsProvider, types: config.CUSTOM_TYPES, rpc: jsonrpc });
setApi(a);
})();
} catch (error) {
throw new Error('Create Api failed.');
}
}, []);
const connect = useCallback(async () => {
if (!api) {
setApiState('CONNECTING');
return;
}
await api.isReady;
setApiState('CONNECT_SUCCESS');
}, [api]);
useEffect(() => {
connect();
}, [connect, api]);
const createApi = (a) => {
setApi(a);
};
const contextValue = {
api,
apiState,
createApi,
};
return <ApiContext.Provider value={contextValue}>{props.children}</ApiContext.Provider>;
}
Example #27
Source File: notification-item.component.js From viade_es2a with BSD 2-Clause "Simplified" License | 5 votes |
NotificationItem = ({ notification, markAsRead, children, deleteNotification }: Props) => {
const { read } = notification;
const currentRead = read ? JSON.parse(read) : false;
const { actor } = notification;
/**
* Redirect notification if it's coming with target
* @type {Function}
*/
const redirectTo = useCallback(async () => {
if (notification.target) {
await markAsRead(notification.path, notification.id);
window.location = notification.target;
}
}, [notification]);
/**
* @TODO: send boolean to pod like boolean and not string
*/
const opCurrentRead = !currentRead;
const defaultImage = 'img/icon/empty-profile.svg';
const actorImage =
notification && notification.actor && notification.actor.image
? notification.actor.image
: defaultImage;
return (
<Item read={currentRead}>
<a href={notification.actor && notification.actor.webId}>
<Img
src={actorImage}
alt="Creator"
onError={e => {
e.target.onerror = null;
e.target.src = defaultImage;
}}
/>
</a>
<Body>
<Message onClick={redirectTo}>
<strong>{actor && actor.name}</strong> {notification.summary}
</Message>
<Meta>
<span className="moment">{moment(notification.published).fromNow()}</span>
{children}
</Meta>
</Body>
<MarkAsRead
type="button"
className="delete"
onClick={() =>
markAsRead(notification.path, notification.id, opCurrentRead ? 'true' : 'false')
}
>
<FontAwesomeIcon icon={currentRead ? 'eye-slash' : 'eye'} />
</MarkAsRead>
<Delete
type="button"
className="delete"
onClick={() => deleteNotification(notification.path)}
>
<FontAwesomeIcon icon="times-circle" />
</Delete>
</Item>
);
}
Example #28
Source File: ParseUsfm.js From usfm-grammar-online with MIT License | 5 votes |
function ParseUsfm() {
const classes = useStyles();
const {
usfmValue,
setJsonValue,
setTabValue,
alert,
mode,
type,
setType,
setOpen,
} = useContext(GrammarContext);
const parseText = useCallback(() => {
if (usfmValue === "") {
return alert("warning", "No USFM Data to Convert");
}
setJsonValue("");
setOpen(true);
setTabValue(0);
setTimeout(() => {
usfmParser();
}, 500);
const usfmParser = () => {
const typeMode = type === "all" ? null : grammar.FILTER.SCRIPTURE;
try {
const myUsfmParser =
mode === "relaxed"
? new grammar.USFMParser(usfmValue, grammar.LEVEL.RELAXED)
: new grammar.USFMParser(usfmValue);
setJsonValue(
JSON.stringify(myUsfmParser.toJSON(typeMode), undefined, 2)
);
} catch (e) {
setJsonValue(e.toString());
alert("error", "Error parsing USFM data");
}
setOpen(false);
};
}, [alert, mode, setJsonValue, setOpen, setTabValue, type, usfmValue]);
useEffect(() => {
if (type === "scripture") {
parseText();
setType("all");
}
}, [type, setType, parseText]);
return (
<div>
<Tooltip title="Convert">
<Button
variant="contained"
color="primary"
onClick={parseText}
endIcon={<KeyboardArrowRightIcon />}
className={classes.button}
>
<span className={classes.buttonText}>Convert</span>
</Button>
</Tooltip>
</div>
);
}
Example #29
Source File: useAPIRequest.js From Legacy with Mozilla Public License 2.0 | 5 votes |
export default function useAPIRequest (reqData, includeStatus, waitForAll) {
// Convert to Array if not already
const isArray = Array.isArray(reqData);
if(!isArray) reqData = [reqData];
// Stringify RequestData
const stringifiedData = reqData.map(i=>i?stringify({...i,extraData:undefined}):i);
// Add Requests
const dispatch = useDispatch();
useFocusEffect(
useCallback(() => {
for(let req of reqData.filter(i=>i)) dispatch(request.add({...req,extraData:undefined}));
return () => {
for(let req of reqData.filter(i=>i)) dispatch(request.remove({...req,extraData:undefined}));
};
},[stringify(reqData)])
)
// Get Request Responses
const raw_data = useSelector(i => stringifiedData.map(req=>req?i.request_data[req]:undefined));
const [data,setData] = useState([]);
useEffect(()=>{
var d = [];
var i = 0;
for(let dat of raw_data) {
if(waitForAll && raw_data.some(i=>!i)) {
d.push(null);
} else if(dat&&data[i]&&dat.id===data[i].id) {
d.push(data[i]);
} else if(dat&&dat.data&&reqData[i].function) {
d.push({
data: reqData[i].function(dat.data)
})
} else {
d.push(dat);
}
i++;
}
setData(d);
},[stringify([...raw_data.map(i=>i?.id),...reqData.map(i=>stringify(i?.extraData))])])
if(includeStatus) {
// If Input is not array, return first element of Array
if(!isArray) return data[0] ? {
data: data[0]?.data,
status: data[0]?.status
} : {
data: undefined,
status: "loading"
};
// Return Array
return data.map(i=>i?({
data: i?.data,
status: i?.status
}):({
data: undefined,
status: "loading"
}));
}
// If Input is not array, return first element of Array
if(!isArray) return data[0]?.data;
// Return Array
return data.map(i=>i?.data);
}