react#useEffect TypeScript Examples
The following examples show how to use
react#useEffect.
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: utils.ts From anchor-web-app with Apache License 2.0 | 7 votes |
useExecuteOnceWhen = (
execute: () => void,
when: () => boolean,
) => {
const [executed, setExecuted] = useState<boolean>();
useEffect(() => {
if (!executed && when()) {
setExecuted(true);
execute();
}
}, [executed, setExecuted, when, execute]);
}
Example #2
Source File: LoadAssets.tsx From react-native-meetio with MIT License | 7 votes |
LoadAssets = ({ assets, fonts, children }: LoadAssetsProps) => {
const [isNavigationReady, setIsNavigationReady] = useState(!__DEV__);
const [initialState, setInitialState] = useState<InitialState | undefined>();
const ready = useLoadAssets(assets || [], fonts || {});
useEffect(() => {
const restoreState = async () => {
try {
const savedStateString = await AsyncStorage.getItem(
NAVIGATION_STATE_KEY
);
const state = savedStateString
? JSON.parse(savedStateString)
: undefined;
setInitialState(state);
} finally {
setIsNavigationReady(true);
}
};
if (!isNavigationReady) {
restoreState();
}
}, [isNavigationReady]);
const onStateChange = useCallback((state) => {
AsyncStorage.setItem(NAVIGATION_STATE_KEY, JSON.stringify(state));
}, []);
if (!ready || !isNavigationReady) {
return <AppLoading />;
}
return (
<NavigationContainer {...{ onStateChange, initialState }}>
{children}
</NavigationContainer>
);
}
Example #3
Source File: useDebounce.tsx From one-platform with MIT License | 6 votes |
useDebounce = <T extends unknown>(value: T, delay = 500): T => {
// State and setters for debounced value
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(
() => {
// Update debounced value after delay
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Cancel the timeout if value changes (also on delay change or unmount)
// This is how we prevent debounced value from updating if value is changed ...
// .. within the delay period. Timeout gets cleared and restarted.
return () => {
clearTimeout(handler);
};
},
[value, delay] // Only re-call effect if value or delay changes
);
return debouncedValue;
}
Example #4
Source File: Select.tsx From Demae with MIT License | 6 votes |
useSelect = (props: InitProps | InitValue) => {
if (typeof props === "string" || typeof props === "number" || typeof props === "boolean" || typeof props === "undefined" || props === null) {
const [value, setValue] = useState(props || "")
useEffect(() => {
setValue(props || "")
}, [props])
const handleChange = e => setValue(e.target.value)
return {
value,
setValue,
onChange: handleChange
};
} else {
const [value, setValue] = useState(props.initValue ? props.initValue : "")
useEffect(() => {
setValue(props.initValue ? props.initValue : "")
}, [props.initValue])
const handleChange = e => setValue(e.target.value)
return {
...props.inputProps,
value,
setValue,
onChange: handleChange
};
}
}
Example #5
Source File: router.tsx From react_admin with MIT License | 6 votes |
Routers: React.FC<Iprops> = (props) => {
useEffect(() => {
const userinfo = localStorage.getItem("userinfo");
/**
* sessionStorage中有user信息,但store中没有
* 说明刷新了页面,需要重新同步user数据到store
* **/
if (userinfo && !props.userinfo.uid) {
props.setUserInfoMy({ _loginName: "admin", _password: "123456" });
}
}, []);
/** 跳转到某个路由之前触发 **/
const onEnter = useCallback((Component, props) => {
/**
* 有用户信息,说明已登录
* 没有,则跳转至登录页
* **/
const userinfo = localStorage.getItem("userinfo");
if (userinfo) {
return <Component {...props} />;
}
return <Redirect to="/" />;
}, []);
return (
<HashRouter>
<Suspense fallback={<Loading />}>
<Switch>
<Route exact path="/" component={Login} />
<Route path="/home" render={(props) => onEnter(BasicLayout, props)} />
</Switch>
</Suspense>
</HashRouter>
);
}
Example #6
Source File: Code.tsx From 35d-blog with MIT License | 6 votes |
Code = ({ children, language }) => {
useEffect(() => {
Prism.highlightAll()
}, [])
return (
<pre className="relative">
<p className="absolute bottom-0 right-4 text-gray-800 text-xs font-semibold bg-gray-200 mb-0 px-2 py-[2px]">
{getLanguageLabel(language)}
</p>
<code
dangerouslySetInnerHTML={{
__html: Prism.highlight(children, Prism.languages[language]),
}}
/>
<style jsx>{`
code {
vertical-align: middle;
white-space: pre;
word-break: break-all;
max-width: 100%;
display: block;
font-size: 0.8rem;
line-height: 1.4;
padding: 1.25rem 1.5rem;
margin: 0.85rem 0;
background-color: #282c34;
color: #ccc;
border-radius: 6px;
overflow: auto;
}
`}</style>
</pre>
)
}
Example #7
Source File: CommunitiesView.tsx From 3Speak-app with GNU General Public License v3.0 | 6 votes |
export function CommunitiesView() {
const [data, setData] = useState([])
const generate = async () => {
const res = await client.call('bridge', 'list_communities', {
last: '',
limit: 100,
})
setData(res)
}
useEffect(() => {
document.title = '3Speak - Tokenised video communities'
generate()
}, [])
return (
<Container fluid>
<Row>
<div className="col-12">
<h3 style={{ display: 'inline-block' }}>Communities</h3>
<span className="float-right mb-3">
<Button id="communityCreate" variant="primary" disabled>
Create +
</Button>
</span>
</div>
</Row>
<Row>
{data.map((value) => (
<CommunityTile key={value.name} reflink={`hive:${value.name}`} info={value} />
))}
</Row>
</Container>
)
}
Example #8
Source File: index.tsx From landy-react-template with MIT License | 6 votes |
ScrollToTop = () => {
const [showScroll, setShowScroll] = useState(false);
const checkScrollTop = (event: any) => {
const offsetFromTop = getScroll(event.target, true);
if (!showScroll && offsetFromTop > 350) {
setShowScroll(true);
} else if (offsetFromTop <= 350) {
setShowScroll(false);
}
};
useEffect(() => {
window.addEventListener("scroll", checkScrollTop);
return () => {
window.removeEventListener("scroll", checkScrollTop);
};
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const scrollUp = () => {
const element = document.getElementById("intro") as HTMLDivElement;
element.scrollIntoView({
behavior: "smooth",
block: "end",
inline: "nearest",
});
};
return (
<ScrollUpContainer onClick={scrollUp} show={showScroll}>
<SvgIcon src="scroll-top.svg" width="20px" height="20px" />
</ScrollUpContainer>
);
}
Example #9
Source File: useMediaQuery.ts From akashlytics with GNU General Public License v3.0 | 6 votes |
export function useMediaQuery(query) {
const [matches, setMatches] = useState(false);
useEffect(() => {
const media = window.matchMedia(query);
if (media.matches !== matches) {
setMatches(media.matches);
}
const listener = () => {
setMatches(media.matches);
};
media.addEventListener("change", listener);
return () => media.removeEventListener("change", listener);
}, [matches, query]);
return matches;
}
Example #10
Source File: App.tsx From overwolf-modern-react-boilerplate with MIT License | 6 votes |
App = () => {
const [page, setPage] = useState<string>('')
useEffect(() => {
async function preLoad() {
if (process.env.NODE_ENV === 'development') {
//you can set the current window to dev if you want to see the dev page <Normal Browser>
setPage(WINDOW_NAMES.DESKTOP)
} else {
const currentWindow = await getCurrentWindow()
setPage(currentWindow)
console.info(
'[? overwolf-modern-react-boilerplate][? src/app/App.tsx][? useEffect - preLoad]',
JSON.stringify({ currentWindow }, null, 2),
)
}
}
preLoad()
}, [])
//this is fallback for the loading current screen
return (
<Suspense fallback={<Loading />}>
<CurrentPage page={page} />
</Suspense>
)
}
Example #11
Source File: index.tsx From react-doc-viewer with Apache License 2.0 | 6 votes |
HTMLRenderer: DocRenderer = ({ mainState: { currentDocument } }) => {
useEffect(() => {
const b64String = currentDocument?.fileData as string;
const bodyBase64 = b64String?.replace("data:text/html;base64,", "") || "";
const body: string = window.atob(bodyBase64);
let iframeCont = document.getElementById(
"html-body"
) as HTMLIFrameElement | null;
let iframe = iframeCont?.contentWindow && iframeCont.contentWindow;
if (!iframe) return;
const iframeDoc = iframe.document;
iframeDoc.open();
iframeDoc.write(`${body}`);
iframeDoc.close();
}, []);
return (
<Container id="html-renderer">
<BodyIFrame id="html-body" sandbox="allow-same-origin" />
</Container>
);
}
Example #12
Source File: decimals.ts From anchor-web-app with Apache License 2.0 | 6 votes |
useERC20Decimals = (tokenContract: string | undefined) => {
const [decimals, setDecimals] = useState<number | undefined>(undefined);
const xAnchor = useEvmCrossAnchorSdk();
useEffect(() => {
async function fetchDecimals() {
if (tokenContract !== undefined) {
const result = await xAnchor.decimals(tokenContract);
setDecimals(result);
}
}
fetchDecimals();
}, [xAnchor, tokenContract]);
return decimals;
}
Example #13
Source File: Reset.tsx From firetable with Apache License 2.0 | 6 votes |
/**
* Reset the form’s values and errors when the Firestore doc’s data updates
*/
export default function Reset({
defaultValues,
dirtyFields,
reset,
getValues,
}: IResetProps) {
useEffect(
() => {
const resetValues = { ...defaultValues };
const currentValues = getValues();
// If the field is dirty, (i.e. the user input a value but it hasn’t been)
// saved to the db yet, keep its current value and keep it marked as dirty
for (const [field, isDirty] of Object.entries(dirtyFields)) {
if (isDirty) {
resetValues[field] = currentValues[field];
}
}
// Compare currentValues to resetValues
const diff = _pickBy(getValues(), (v, k) => !_isEqual(v, resetValues[k]));
// Reset if needed & keep the current dirty fields
if (Object.keys(diff).length > 0) {
reset(resetValues, { isDirty: true, dirtyFields: true });
}
},
// `defaultValues` is the `initialValue` of each field type +
// the current value in the Firestore doc
[JSON.stringify(defaultValues)]
);
return null;
}
Example #14
Source File: index.tsx From vscode-crossnote with GNU Affero General Public License v3.0 | 5 votes |
function KanbanColumnHeaderDisplay(props: KanbanColumnHeaderProps) {
const classes = useStyles(props);
const { t } = useTranslation();
const column = props.column;
const board = props.board;
const isPreview = props.isPreview;
const refreshBoard = props.refreshBoard;
const [clickedTitle, setClickedTitle] = useState<boolean>(false);
const [titleValue, setTitleValue] = useState<string>(column.title);
useEffect(() => {
if (!clickedTitle && titleValue !== column.title) {
column.title = titleValue || t("general/Untitled");
setTitleValue(column.title);
refreshBoard(board);
}
}, [clickedTitle, board, column.title, titleValue, t, refreshBoard]);
return (
<Box className={clsx(classes.columnHeader)}>
<Box>
{clickedTitle ? (
<TextField
value={titleValue}
onChange={(event) => {
setTitleValue(event.target.value);
}}
onBlur={() => {
setClickedTitle(false);
}}
onKeyUp={(event) => {
if (event.which === 13) {
setClickedTitle(false);
}
}}
></TextField>
) : (
<Typography
variant={"body1"}
style={{ cursor: "text" }}
onClick={() => {
if (!isPreview) {
setClickedTitle(true);
}
}}
>
{titleValue}
</Typography>
)}
</Box>
{!isPreview && (
<Box>
<IconButton
onClick={() => {
const card: KanbanCard = {
id: Date.now(),
title: "", //"Card " + column.cards.length,
description: t("general/empty"),
};
if (column) {
column.cards.push(card);
}
props.refreshBoard(board);
}}
>
<CardPlus></CardPlus>
</IconButton>
<IconButton
onClick={() => {
board.columns = board.columns.filter((l) => column.id !== l.id);
props.refreshBoard(board);
}}
>
<Close></Close>
</IconButton>
</Box>
)}
</Box>
);
}
Example #15
Source File: AsyncSelect.tsx From one-platform with MIT License | 5 votes |
AsyncSelect = ({
render,
onSelect,
customFilter,
onTypeaheadInputChanged,
...selectProps
}: Props): JSX.Element => {
const [isOpen, setIsOpen] = useToggle();
const [options, setOptions] = useState<ReactElement<any, string | JSXElementConstructor<any>>[]>(
[]
);
const [typeAhead, setTypeAhead] = useState('');
useEffect(() => {
if (!isOpen) {
setTypeAhead('');
setOptions([]);
return;
}
setOptions(LOADING);
render(typeAhead)
.then((loadedOptions) => {
setOptions(loadedOptions);
})
.catch(() => {
setOptions([
<SelectOption
key="option-error"
value="Failed to fetch request"
isPlaceholder
isDisabled
/>,
]);
});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [typeAhead, isOpen]);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const onPfeSelect = (...args: any) => {
// eslint-disable-next-line prefer-spread
onSelect?.apply(null, args);
setIsOpen.off();
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const onPfeTypeAheadChange = (value: string) => {
setTypeAhead(value);
// eslint-disable-next-line prefer-spread
if (onTypeaheadInputChanged) onTypeaheadInputChanged(value);
};
const onFilter = (a: ChangeEvent<HTMLInputElement> | null, value: string) => {
if (!value) {
return options;
}
if (!customFilter) return options;
return options.filter((child) => customFilter(child));
};
return (
<PfeSelect
{...selectProps}
onSelect={onPfeSelect}
isOpen={isOpen}
onToggle={setIsOpen.toggle}
onTypeaheadInputChanged={onPfeTypeAheadChange}
onFilter={customFilter && onFilter}
>
{options}
</PfeSelect>
);
}
Example #16
Source File: Input.tsx From Demae with MIT License | 5 votes |
useInput = (props: InitProps | InitValue, textFieldProps?: TextFieldProps) => {
if (typeof props === 'string' || typeof props === 'undefined' || typeof props === 'number' || props === null) {
const initValue = String(props || '')
const [value, setValue] = useState(initValue)
const [error, setError] = useState(false)
useEffect(() => {
setValue(initValue)
}, [])
const onChange = e => {
const value = e.target.value
setValue(value)
if (textFieldProps && value && error) {
const inputProps = (textFieldProps as any).inputProps
if (inputProps) {
const pattern = inputProps.pattern
if (pattern) {
const regex = new RegExp(pattern)
setError(!value.match(regex))
}
}
}
}
const onBlur = e => {
const value = e.target.value
if (textFieldProps && value) {
const inputProps = (textFieldProps as any).inputProps
if (inputProps) {
const pattern = inputProps.pattern
if (pattern) {
const regex = new RegExp(pattern)
setError(!value.match(regex))
}
}
}
}
return {
...textFieldProps,
value,
error,
setValue,
onChange: onChange,
onBlur: onBlur
};
} else {
const [value, setValue] = useState(props.initValue ? props.initValue : '')
useEffect(() => {
setValue(props.initValue ? props.initValue : '')
}, [props.initValue])
const handleChange = e => setValue(e.target.value)
return {
...props.inputProps,
value,
setValue,
onChange: handleChange
};
}
}
Example #17
Source File: index.tsx From react_admin with MIT License | 5 votes |
Echarts: React.FC<Props> = () => {
/**
* 初始化数据
*/
const [data, setData] = useState<any>()
useEffect(() => {
const arr = [820, 932, 901, 934, 1290, 1330, 1620]
setData([...arr])
}, [])
/**
* echarts配置项
*/
const getOption = {
title: {
text: '名字\n很香',
subtext: '副标题',
},
tooltip: {
trigger: 'item',
},
legend: {
data: ['星期'],
},
toolbox: {
show: true,
feature: {
dataView: {
show: true,
readOnly: false,
},
magicType: {
type: ['line', 'bar', 'stack', 'tiled'],
},
restore: {
show: true,
},
saveAsImage: {
show: true,
type: 'jpg',
},
},
},
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
name: '星期几',
position: 'bottom',
nameLocation: 'end',
nameTextStyle: {
color: 'red',
fontWeight: 'bold',
},
},
yAxis: {
type: 'value',
},
series: [
{
name: '星期',
data,
type: 'bar',
areaStyle: {},
},
],
}
/**
* 进行渲染
*/
return (
<ReactEcharts
option={getOption}
notMerge={true}
lazyUpdate={true}
theme={'theme_name'}
/>
)
}
Example #18
Source File: StartUp.tsx From 3Speak-app with GNU General Public License v3.0 | 5 votes |
export function StartUp(props: any) {
const [show, setShow] = useState(false)
const [message, setMessage] = useState('')
useEffect(() => {
const load = async () => {
const backendStatus = (await PromiseIpc.send('core.status', undefined as any)) as any
if (backendStatus.ready === false) {
setShow(true)
const pid = setInterval(async () => {
const status = (await PromiseIpc.send('core.status', undefined as any)) as any
setMessage(status.start_progress.message)
}, 25)
PromiseIpc.send('core.ready', undefined as any).then((eda) => {
setShow(false)
clearInterval(pid)
})
}
}
void load()
}, [])
return (
<div>
<Modal show={show} backdrop={'static'} backdropClassName={'start-backdrop'}>
<Modal.Header>
<Modal.Title>App Starting Up</Modal.Title>
</Modal.Header>
<Modal.Body>
<div style={{ textAlign: 'center' }}>
<h1 style={{ paddingTop: '50px' }}>Loading</h1>
<hr />
<p style={{ fontSize: '15px' }}>{message}</p>
</div>
</Modal.Body>
</Modal>
</div>
)
}
Example #19
Source File: useForm.tsx From landy-react-template with MIT License | 5 votes |
useForm = (validate: any) => {
const [values, setValues] = useState({});
const [errors, setErrors] = useState({});
const [shouldSubmit, setShouldSubmit] = useState(false);
const openNotificationWithIcon = () => {
notification["success"]({
message: "Success",
description: "Your message has been sent!",
});
};
const handleSubmit = (event: React.ChangeEvent<HTMLFormElement>) => {
event.preventDefault();
setErrors(validate(values));
// Your url for API
const url = "";
if (Object.keys(values).length === 3) {
axios
.post(url, {
...values,
})
.then(() => {
setShouldSubmit(true);
});
}
};
useEffect(() => {
if (Object.keys(errors).length === 0 && shouldSubmit) {
setValues("");
openNotificationWithIcon();
}
}, [errors, shouldSubmit]);
const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
event.persist();
setValues((values) => ({
...values,
[event.target.name]: event.target.value,
}));
setErrors((errors) => ({ ...errors, [event.target.name]: "" }));
};
return {
handleChange,
handleSubmit,
values,
errors,
};
}
Example #20
Source File: PinnedVideo.tsx From ReactNative-UIKit with MIT License | 5 votes |
PinnedVideo: React.FC = () => {
const {rtcProps, styleProps} = useContext(PropsContext);
const [width, setWidth] = useState(Dimensions.get('screen').width);
useEffect(() => {
Dimensions.addEventListener('change', () => {
setWidth(Dimensions.get('screen').width);
});
});
return (
<>
<MaxUidConsumer>
{(maxUsers) =>
maxUsers[0] ? ( // check if audience & live don't render if uid === local
<MaxVideoView user={maxUsers[0]} key={maxUsers[0].uid} />
) : null
}
</MaxUidConsumer>
<ScrollView
showsHorizontalScrollIndicator={false}
horizontal={true}
style={{
...styles.minContainer,
width: width,
...(styleProps?.minViewContainer as Object),
}}>
<MinUidConsumer>
{(minUsers) =>
minUsers.map((user) =>
rtcProps.role === ClientRole.Audience &&
user.uid === 'local' ? null : (
<MinVideoView user={user} key={user.uid} showOverlay={true} />
),
)
}
</MinUidConsumer>
</ScrollView>
</>
);
}
Example #21
Source File: BetaBanner.tsx From akashlytics with GNU General Public License v3.0 | 5 votes |
BetaBanner = () => {
const [isBetaBarVisible, setIsBetaBarVisible] = useState(false);
const classes = useStyles();
useEffect(() => {
const isBetaBarSeen = localStorage.getItem("isBetaBarSeen");
setIsBetaBarVisible(isBetaBarSeen === null ? true : false);
}, []);
const hideIsBetaBarVisible = () => {
localStorage.setItem("isBetaBarSeen", "true");
setIsBetaBarVisible(false);
};
return (
<>
{isBetaBarVisible && (
<AppBar position="static" color="default" className={classes.root}>
<Toolbar>
<Chip label="BETA" color="primary" className={classes.betaChip} />
<div className={classes.betaText}>
<Box marginBottom=".5rem">
<Typography variant="body2">
Akashlytics Deploy is now currently in open BETA.
</Typography>
</Box>
<Button
component={Link}
to="/deploy"
variant="contained"
size="small"
onClick={() => hideIsBetaBarVisible()}
>
Take a look!
</Button>
</div>
<div className={classes.grow} />
<IconButton
aria-label="Close beta app bar"
color="inherit"
onClick={() => hideIsBetaBarVisible()}
>
<CloseIcon />
</IconButton>
</Toolbar>
</AppBar>
)}
</>
);
}
Example #22
Source File: useGameEventProvider.ts From overwolf-hooks with MIT License | 5 votes |
useGameEventProvider = <GameInfo, GameEvent>({
displayLog,
}: {
displayLog?: boolean
}) => {
const [info, setInfo] = useState<GameInfo>()
const [event, setEvent] = useState<GameEvent[]>()
const [requiredFeatures, setFeatures] = useState<string[]>([])
function handleGameEvent({ info, events }: GameEventData<any, any>) {
info && setInfo(info)
events && setEvent(events)
}
{
}
const registerToGepCallback = useCallback(
({ success, ...rest }: { success: boolean }) => {
if (success) {
Overwolf.onInfoUpdates2.removeListener(handleGameEvent)
Overwolf.onNewEvents.removeListener(handleGameEvent)
Overwolf.onInfoUpdates2.addListener(handleGameEvent)
Overwolf.onNewEvents.addListener(handleGameEvent)
} else
setTimeout(() => {
Overwolf.setRequiredFeatures(requiredFeatures, registerToGepCallback)
}, REGISTER_RETRY_TIMEOUT)
displayLog &&
console.info(
'[? overwolf-hooks][? useGameEventProvider][? registerToGepCallback]',
JSON.stringify({ success, ...rest }, null, 2),
)
},
[requiredFeatures],
)
const runGep = useCallback(() => {
Overwolf.setRequiredFeatures(requiredFeatures, registerToGepCallback)
}, [requiredFeatures, registerToGepCallback])
const setGameFeatures = useCallback(setFeatures, [])
useEffect(() => {
requiredFeatures.length && runGep()
return () => {
Overwolf.onInfoUpdates2.removeListener(handleGameEvent)
Overwolf.onNewEvents.removeListener(handleGameEvent)
}
}, [runGep, requiredFeatures])
return [{ info, event }, setGameFeatures] as const
}
Example #23
Source File: BackgroundWindow.tsx From overwolf-modern-react-boilerplate with MIT License | 5 votes |
BackgroundWindow = () => {
const [currentGame] = useRunningGame(OVERWOLF_HOOKS_OPTIONS)
const [desktopWindow] = useWindow(DESKTOP, OVERWOLF_HOOKS_OPTIONS)
const [ingameWindow] = useWindow(INGAME, OVERWOLF_HOOKS_OPTIONS)
const [{ event, info }, setGameFeatures] = useGameEventProvider<
HeathstoneOverwolfGEP.Info,
HeathstoneOverwolfGEP.Event
>(OVERWOLF_HOOKS_OPTIONS)
const dispatch = useDispatch()
const openStartupWindow = useCallback(() => {
const gameRunning =
currentGame?.id === Game.HearhtStone &&
(currentGame?.gameRunning || currentGame?.gameChanged)
const currentWindow = gameRunning ? ingameWindow : desktopWindow
gameRunning && setGameFeatures(REQUIRED_FEATURES)
currentWindow?.restore()
}, [desktopWindow, ingameWindow, currentGame, setGameFeatures])
useEffect(() => {
event && dispatch(setEvent({ event }))
}, [event, dispatch])
useEffect(() => {
info && dispatch(setInfo({ info }))
}, [info, dispatch])
useEffect(() => {
openStartupWindow()
}, [openStartupWindow])
return <></>
}
Example #24
Source File: index.tsx From react-doc-viewer with Apache License 2.0 | 5 votes |
MSGRenderer: DocRenderer = ({ mainState: { currentDocument } }) => {
const [fileData, setFileData] = useState<MSGFileData | MSGErrorResult>();
useEffect(() => {
if (!currentDocument || !currentDocument.fileData) return;
const _fd = new MSGReader(
currentDocument.fileData as ArrayBuffer
).getFileData();
setFileData(_fd);
}, [currentDocument?.fileData]);
useEffect(() => {
if (!fileData || fileData.hasOwnProperty("error")) return;
let iframeCont = document.getElementById(
"msg-body"
) as HTMLIFrameElement | null;
let iframe = iframeCont?.contentWindow && iframeCont.contentWindow;
if (!iframe) return;
const iframeDoc = iframe.document;
let body = (fileData as MSGFileData).body.replace(
/(\r\n|\n|\r)/gm,
"<br />"
);
iframeDoc.open();
iframeDoc.write(`${body}`);
iframeDoc.close();
}, [fileData]);
if (!fileData || fileData.hasOwnProperty("error")) {
return <span>{(fileData as MSGErrorResult)?.error}</span>;
}
let {
recipients,
subject,
senderEmail,
senderName,
} = fileData as MSGFileData;
return (
<Container id="msg-renderer">
<h2 id="msg-subject-title" style={{ marginBottom: 0 }}>
{subject}
</h2>
<Sender name={senderName} email={senderEmail} />
<RecipientContainer id="msg-recipient">
<h3 id="msg-recipient-title">Recipients</h3>
<ul id="msg-recipient-ul">
{recipients.map((r, i) => (
<li key={i} id="msg-recipient-li">
<span id="msg-recipient-name">{r.name}</span>
{r.hasOwnProperty("email") && (
<span id="msg-recipient-email"> - {r.email}</span>
)}
</li>
))}
</ul>
</RecipientContainer>
<BodyIFrame id="msg-body" sandbox="allow-same-origin" />
</Container>
);
}
Example #25
Source File: Main.tsx From twitch-clone with MIT License | 5 votes |
Main = () => {
const [data, setData] = useState<DataProps[]>();
useEffect(() => {
getData();
}, []);
async function getData() {
const response = await axios.get(
`https://api.twitch.tv/kraken/streams?limit=30&offset=${Math.floor(
Math.random() * 100,
)}`,
{
headers: {
Accept: 'application/vnd.twitchtv.v5+json',
'Client-Id': 'l4ulgpuzjl21kfkklj0k7aycw7ho72o', // this is a "public" client-id, i always hide my private keys in a .env file
},
},
);
setData(response.data.streams);
}
if (!data) {
return (
<Container>
<div className="loading-container">
<h1>Twitch Clone</h1>
<div className="loading"></div>
</div>
</Container>
);
}
return (
<Container>
<VideoCarousel data={data} />
<VideoGroup data={data} />
<VideoGroup data={data} />
<VideoGroup data={data} />
<VideoGroup data={data} />
</Container>
);
}
Example #26
Source File: txHistory.ts From anchor-web-app with Apache License 2.0 | 5 votes |
export function useMypageTxHistoryQuery(): TxHistoryReturn {
const { connected, terraWalletAddress } = useAccount();
const { indexerApiEndpoint: endpoint } = useAnchorWebapp();
const [history, setHistory] = useState<MypageTxHistory[]>([]);
const [next, setNext] = useState<string | null>(null);
const [inProgress, setInProgress] = useState<boolean>(true);
const load = useCallback(() => {
// initialize data
setHistory([]);
setNext(null);
if (!connected || !terraWalletAddress) {
setInProgress(false);
return;
}
setInProgress(true);
mypageTxHistoryQuery({
endpoint,
walletAddress: terraWalletAddress,
offset: null,
})
.then(({ history, next }) => {
setInProgress(false);
setHistory(history);
setNext(next);
})
.catch((error) => {
console.error(error);
setHistory([]);
setNext(null);
setInProgress(false);
});
}, [connected, terraWalletAddress, endpoint]);
const loadMore = useCallback(() => {
if (history.length > 0 && !!next && connected && terraWalletAddress) {
setInProgress(true);
mypageTxHistoryQuery({
endpoint,
walletAddress: terraWalletAddress,
offset: next,
}).then(({ history, next }) => {
setHistory((prev) => {
return Array.isArray(history) && history.length > 0
? [...prev, ...history]
: prev;
});
setNext(next);
setInProgress(false);
});
}
}, [connected, terraWalletAddress, endpoint, history.length, next]);
useEffect(() => {
load();
}, [load]);
return {
history,
isLast: !next,
reload: load,
loadMore,
inProgress,
};
}