How to use the preact/hooks.useEffect function in preact

To help you get started, we’ve selected a few preact examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github GoogleChrome / lighthouse-ci / packages / server / src / ui / hooks / use-api-data.jsx View on Github external
function useApiData(apiMethod, apiParameters) {
  const [loadingState, setLoadingState] = useState(/** @type {LoadingState} */ ('loading'));
  const [apiData, setApiData] = useState(/** @type {any} */ (undefined));

  useEffect(() => {
    if (!apiParameters) return;

    // Wrap in IIFE because the return value of useEffect should be a cleanup function, not a Promise.
    (async () => {
      try {
        // @ts-ignore - tsc can't figure out that apiParameters matches our apiMethod signature
        const response = await api[apiMethod](...apiParameters);
        setApiData(response);
        setLoadingState('loaded');
      } catch (err) {
        console.error(err); // eslint-disable-line no-console
        setLoadingState('error');
      }
    })();
  }, apiParameters);
github hypothesis / client / src / sidebar / components / annotation-share-control.js View on Github external
isPrivate,
  shareUri,
}) {
  const shareRef = useRef();
  const inputRef = useRef();

  const [isOpen, setOpen] = useState(false);
  const wasOpen = useRef(isOpen);

  const toggleSharePanel = () => setOpen(!isOpen);
  const closePanel = () => setOpen(false);

  // Interactions outside of the component when it is open should close it
  useElementShouldClose(shareRef, isOpen, closePanel);

  useEffect(() => {
    if (wasOpen.current !== isOpen) {
      wasOpen.current = isOpen;
      if (isOpen) {
        // Panel was just opened: select and focus the share URI for convenience
        inputRef.current.focus();
        inputRef.current.select();
      }
    }
  }, [isOpen]);

  // FIXME: See https://github.com/hypothesis/client/issues/1542
  if (!group) {
    return null;
  }

  const copyShareLink = () => {
github lydell / LinkHints / src / options / TextInput.js View on Github external
// Move the default cursor position from the end of the textarea to the start.
      textarea ? restoreSelection() : undefined,
    [textarea]
  );

  useLayoutEffect(() => {
    // When readonly textareas change, move the cursor back to the start.
    if (textarea && readonly) {
      selectionStartRef.current = 0;
      selectionEndRef.current = 0;
      return timeout(0, restoreSelection);
    }
    return undefined;
  }, [textarea, readonly, savedValue]);

  useEffect(
    () =>
      // Save after `SAVE_TIMEOUT` ms has passed since the last input.
      focused && !readonly
        ? timeout(SAVE_TIMEOUT, () => {
            const save = saveRef.current;
            if (save != null) {
              const normalizedValue = normalizeRef.current(value);
              if (normalizedValue !== savedValue) {
                save(normalizedValue, "input");
              }
            }
          })
        : undefined,
    [focused, readonly, savedValue, value]
  );
github cheeaun / busrouter-sg / assets / firstlast.js View on Github external
function FirstLastTimes() {
  const [stop, setStop] = useState('     ');
  const [stopName, setStopName] = useState(null);
  const [data, setData] = useState([]);

  const [tableRef, _, tableHeight] = useResizeObserver();
  const [timeLeft, setTimeLeft] = useState(null);
  const [timeStr, setTimeStr] = useState('');

  useEffect(() => {
    Promise.all([
      fetchCache(firstLastJSONPath, 24 * 60),
      fetchCache(stopsJSONPath, 24 * 60),
    ]).then(([flData, stopsData]) => {
      window.onhashchange = () => {
        const stop = location.hash.slice(1);
        const data = flData[stop];
        if (!data) {
          alert('Bus stop code not found.');
          return;
        }

        setStop(stop);
        setStopName(stopsData[stop][2]);
        setData(data.map(d => d.split(/\s+/)).sort((a, b) => sortServices(a[0], b[0])));
github preactjs / preact-www / src / components / controllers / page / index.js View on Github external
export function useTitle(title) {
	useEffect(() => {
		if (title) {
			document.title = `${title} | ${config.title}`;
		}
	}, [title]);
}
github preactjs / preact-devtools / src / view / components / TreeView.tsx View on Github external
export function TreeItem(props: { key: any; id: ID }) {
	const { id } = props;
	const store = useStore();
	const sel = useSelection();
	const { collapsed, toggle } = useCollapser();
	const filterFragments = useObserver(() => store.filter.filterFragment.$);
	const node = useObserver(() => store.nodes.$.get(id) || null);
	const onToggle = () => toggle(id);
	const ref = useRef();

	let isSelected = sel.selected === id;
	useEffect(() => {
		if (ref.current && isSelected) {
			scrollIntoView(ref.current);
		}
	}, [ref.current, sel.selected, id]);

	if (!node) return null;

	return (
		<div class="{s.item}"> sel.selectById(id)}
			onMouseEnter={() =&gt; store.actions.highlightNode(id)}
			data-selected={isSelected}
			data-id={id}
			data-depth={node.depth}</div>
github davidbailey00 / ninetales / packages / head / src / browser / index.js View on Github external
export default function Head({ children }) {
  useEffect(() => {
    if (!ssrHeadTagsPruned) {
      document.querySelectorAll("[data-n-head]").forEach(el => el.remove());
      ssrHeadTagsPruned = true;
    }
  }, []);

  return createPortal(
    Array.isArray(children)
      ? children.map(stripDataJsx)
      : stripDataJsx(children),
    document.head
  );
}
github paypal / paypal-smart-payment-buttons / src / menu / hooks.js View on Github external
export function useAutoFocus() : Object {
    const ref = useRef();

    useEffect(() => {
        if (ref.current) {
            ref.current.focus();
        }
    });

    return ref;
}
github preactjs / preact-devtools / src / view / store / react-bindings.ts View on Github external
let [_, set] = useState(0);
	let count = useRef(0);
	let tmp = useRef(null as any);
	let ref = useRef&gt;(tmp.current || (tmp.current = watch(fn)));

	const dispose = useMemo(() =&gt; {
		let disp = ref.current.on(() =&gt; {
			set((count.current = count.current + 1));
		});
		return () =&gt; {
			disp();
			ref.current._disposers.forEach(disp =&gt; disp());
		};
	}, []);

	useEffect(() =&gt; {
		return () =&gt; dispose();
	}, []);

	return ref.current.$;
}
github preactjs / preact-devtools / src / view / components / DataInput / index.tsx View on Github external
export function DataInput({ value, onChange, name, ...props }: InputProps) {
	const value$ = useRef(valoo(value)).current;
	const tmp = useRef(null as any);
	const store = useRef&gt;(
		(tmp as any).current || (tmp.current = createInputStore(value$)),
	).current;

	useEffect(() =&gt; {
		store.onClear();
	}, [name]);

	useEffect(() =&gt; {
		if (value$.$ !== value) {
			value$.$ = value;
		}
		const dispose = value$.on(v =&gt; onChange(v));
		return () =&gt; dispose();
	}, [value$, value, onChange]);

	const valid = useObserver(() =&gt; store.valid.$);
	const type = useObserver(() =&gt; store.valueType.$);
	const inputVal = useObserver(() =&gt; store.actualValue.$);
	const focus = useObserver(() =&gt; store.focus.$);
	const showReset = useObserver(() =&gt; store.showReset.$);
	const ref = useRef();

	useMemo(() =&gt; {
		if (ref.current) {