How to use the preact/hooks.useState 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 hypothesis / lms / lms / static / scripts / frontend_apps / components / SubmitGradeForm.js View on Github external
// State for loading the grade
  const { grade, gradeLoading } = useFetchGrade(student);

  // The following is state for saving the grade
  //
  // If there is an error when submitting a grade?
  const [submitGradeError, setSubmitGradeError] = useState('');
  // Is set to true when the grade is being currently posted to the service
  const [gradeSaving, setGradeSaving] = useState(false);
  // Changes the input field's background to green for a short duration when true
  const [gradeSaved, setGradeSaved] = useState(false);

  // The following is state for local validation errors
  //
  // Is there a validation error message to show?
  const [showValidationError, setValidationError] = useState(false);
  // The actual validation error message.
  const [validationMessage, setValidationMessageMessage] = useState('');
  // Unique id attribute for <input>
  const gradeId = useUniqueId('SubmitGradeForm__grade:');

  const {
    api: { authToken },
  } = useContext(Config);

  // Used to handle keyboard input changes for the grade input field.
  const inputRef = useRef(/** @type {HTMLInputElement|null} */ (null));

  // Clear the previous grade saved status when the user changes.
  useEffect(() =&gt; {
    setGradeSaved(false);
  }, [student]);
github preactjs / preact-devtools / src / view / components / TreeView.tsx View on Github external
export function HighlightPane(props: { treeDom: HTMLDivElement | null }) {
	const store = useStore();
	const nodes = useObserver(() => store.nodes.$);
	const { selected } = useSelection();
	const { collapsed } = useCollapser();

	// Subscribe to nodeList so that we rerender whenever nodes
	// are collapsed
	const list = useObserver(() => store.nodeList.$);

	let [pos, setPos] = useState({ top: 0, height: 0 });
	useEffect(() => {
		if (selected > -1 && !collapsed.has(selected)) {
			if (props.treeDom != null) {
				let start = props.treeDom.querySelector(
					`[data-id="${selected}"`,
				) as HTMLDivElement | null;
				let lastId = getLastChild(nodes, selected);
				let last = props.treeDom.querySelector(
					`[data-id="${lastId}"]`,
				) as HTMLDivElement | null;

				if (start != null && last != null) {
					const rect = start.getBoundingClientRect();
					const top = start.offsetTop + rect.height;
					const lastRect = last.getBoundingClientRect();
					let height = last.offsetTop + lastRect.height - top;
github preactjs / preact-www / src / components / header / gh-version.js View on Github external
export default function ReleaseLink(props) {
	const [url, setUrl] = useState(URL);
	const [version, setVersion] = useState(VERSION);
	useEffect(() =&gt; {
		fetchRelease(config.repo)
			.catch(() =&gt; ({
				version: VERSION,
				url: URL
			}))
			.then(d =&gt; {
				setVersion(d.version);
				setUrl(d.url);
			});
	}, []);

	return (
		<a href="{url}">
			v{version}
		</a>
github preactjs / preact-integrations / src / shared / lib / useOverlayToggle.js View on Github external
export function useOverlayToggle() {
	const [open, setOpen] = useState(false);

	function onResize() {
		if (open) setHeight();
	}

	useEffect(onResize, [open]);
	useEffect(() => {
		window.addEventListener('resize', onResize);
		return () => window.removeEventListener('resize', onResize);
	}, [open]);

	return [open, setOpen];
}
github lydell / LinkHints / src / options / ButtonWithPopup.js View on Github external
popupContent,
  onChange,
  className = "",
  ...restProps
}: {
  buttonContent: React.Node,
  popupContent: ({ close: () =&gt; void }) =&gt; React.Node,
  open?: boolean,
  onChange?: boolean =&gt; void,
  className?: string,
  ...
}) {
  const onChangeRef = useRef();
  onChangeRef.current = onChange;

  const [openState, setOpenState] = useState(false);

  const open = openProp != null ? openProp : openState;

  const rootRef = useRef();

  const setOpen = useCallback(
    newOpen =&gt; {
      if (openProp == null) {
        setOpenState(newOpen);
      }
      if (onChangeRef.current != null) {
        onChangeRef.current(newOpen);
      }
    },
    [openProp]
  );
github yuanqing / create-figma-plugin / packages / ui / src / components / layer / layer.stories.js View on Github external
export const ComponentSelected = function () {
  const [isSelected, setIsSelected] = useState(true)
  function handleClick () {
    setIsSelected(!(isSelected === true))
  }
  return (
    
      Text
    
  )
}
github Houdou / arkgraph / src / routes / farming / index.js View on Github external
const ArkFarming = ({
	config,
	data,
	planner_service,
	level_id: level_query,
}) => {
	const {
		state: { stock, records, compound_materials },
		load,
		adjustStockItem,
	} = data;

	const summary = useMemo(() => sumRequirements(records, stock, compound_materials), [records, stock, compound_materials]);

	const [level_id, setLevelId_raw] = useState(global.level_query);
	const [grouping_type, setGroupingType_raw] = useState(global.grouping_type || 'default');
	const [filter_type, setFilterType_raw] = useState(global.filter_type || 'shortage');

	const filters = {
		shortage: item => summary[item.id] && Math.max(summary[item.id] - (stock[item.id] || 0), 0) > 0,
		required: item => summary[item.id],
		exceeded: item => Math.max((stock[item.id] || 0) - summary[item.id], 0) > 0,
	};

	const itemFilter = filters[filter_type] || null;

	const setLevelId = (id) => {
		if (id && typeof id === 'string') {
			try {
				global.ga('send', {
					hitType: 'event',
					eventCategory: 'farming_level_filter',
github kidqueb / preact-polka-ssr / src / client / pages / Sports.js View on Github external
const Sports = ({ req, params }) =&gt; {
  const [clicks, setClicks] = useState(0);

	return (
		<div>
			<h1>Sports</h1>
			<code>
				ID: {params.id}<br>
				Segment: {params.segment}
			</code>
			<p>{clicks}</p>
			<p>
				<button> setClicks(clicks + 1)}&gt;Add</button>
			</p>

      asd
      
			</div>
github Houdou / arkgraph / src / components / app.js View on Github external
const App = (props) => {
	const [currentUrl, setCurrentUrl] = useState('/');
	const {
		config,
		load,
		toggleShowAllResources,
		toggleShowFocusMaterials,
		toggleShowFilter,
		toggleShowExp,
		toggleShowAnnouncementCodeOnce,
		setFilters,
	} = useConfig();

	const [drops, setDrops] = useState([]);

	const data = useData();

	useEffect(() => {
github the-fast-track / book-5.0-4 / spa / src / pages / conference.js View on Github external
export default function Conference({conferences, slug}) {
    const conference = conferences.find(conference =&gt; conference.slug === slug);
    const [comments, setComments] = useState(null);

    useEffect(() =&gt; {
        findComments(conference).then(comments =&gt; setComments(comments));
    }, [slug]);

    return (
        <div>
            <h4>{conference.city} {conference.year}</h4>
            
        </div>
    );
}