How to use the @wordpress/element.useEffect function in @wordpress/element

To help you get started, we’ve selected a few @wordpress/element 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 ampproject / amp-wp / assets / src / onboarding-wizard / components / user-context-provider.js View on Github external
export function UserContextProvider( { children, userOptionDeveloperTools, userRestPath } ) {
	const { originalOptions, fetchingOptions } = useContext( Options );
	const [ fetchingUser, setFetchingUser ] = useState( false );
	const [ developerToolsOption, setDeveloperToolsOption ] = useState( null );
	const [ originalDeveloperToolsOption, setOriginalDeveloperToolsOption ] = useState( null );
	const [ savingDeveloperToolsOption, setSavingDeveloperToolsOption ] = useState( false );
	const [ didSaveDeveloperToolsOption, setDidSaveDeveloperToolsOption ] = useState( false );
	const { setAsyncError } = useAsyncError();

	// This component sets state inside async functions. Use this ref to prevent state updates after unmount.
	const hasUnmounted = useRef( false );
	useEffect( () => () => {
		hasUnmounted.current = true;
	}, [] );

	const hasDeveloperToolsOptionChange = useMemo(
		() => null !== developerToolsOption && developerToolsOption !== originalDeveloperToolsOption,
		[ developerToolsOption, originalDeveloperToolsOption ],
	);
	/**
	 * Fetch user options on mount.
	 */
	useEffect( () => {
		if ( fetchingOptions ) {
			return;
		}

		if ( ! originalOptions.plugin_configured ) {
github Automattic / vip-go-mu-plugins-built / jetpack / extensions / shared / external-media / sources / pexels.js View on Github external
[ getMedia, searchQuery ]
	);

	const previousSearchQueryValue = useRef();
	const onSearch = useCallback(
		event => {
			event.preventDefault();
			setLastSearchQuery( searchQuery );
			getNextPage( event, true );
			previousSearchQueryValue.current = searchQuery;
		},
		[ getNextPage, searchQuery ]
	);

	// Load initial results for the random example query.
	useEffect( getNextPage, [] );

	const searchFormEl = useRef( null );

	const focusSearchInput = () => {
		if ( ! searchFormEl.current ) {
			return;
		}

		const formElements = Array.from( searchFormEl.current.elements );
		// TextControl does not support ref forwarding, so we need to find the input:
		const searchInputEl = formElements.find( element => element.type === 'search' );

		if ( searchInputEl ) {
			searchInputEl.focus();
			searchInputEl.select();
		}
github ampproject / amp-wp / assets / src / edit-story / components / canvas / canvasProvider.js View on Github external
const selectIntersection = useCallback( ( { x: lx, y: ly, width: lw, height: lh } ) => {
		const newSelectedElementIds =
			currentPage.elements.filter( ( { x, y, width, height } ) => {
				return (
					x <= lx + lw &&
					lx <= x + width &&
					y <= ly + lh &&
					ly <= y + height
				);
			} ).map( ( { id } ) => id );
		setSelectedElementsById( { elementIds: newSelectedElementIds } );
	}, [ currentPage, setSelectedElementsById ] );

	// Reset editing mode when selection changes.
	useEffect( () => {
		if ( editingElement &&
        ( selectedElementIds.length !== 1 || selectedElementIds[ 0 ] !== editingElement ) ) {
			clearEditing();
		}
	}, [ editingElement, selectedElementIds, clearEditing ] );

	useCanvasSelectionCopyPaste( pageContainer );

	const transformHandlersRef = useRef( {} );

	const registerTransformHandler = useCallback( ( id, handler ) => {
		const handlerListMap = transformHandlersRef.current;
		const handlerList = ( handlerListMap[ id ] || ( handlerListMap[ id ] = [] ) );
		handlerList.push( handler );
		return () => {
			handlerList.splice( handlerList.indexOf( handler ), 1 );
github ampproject / amp-wp / assets / src / setup / components / reader-themes-context-provider.js View on Github external
if ( true === hasUnmounted.current ) {
					return;
				}
			} catch ( e ) {
				setError( e );
				return;
			}

			setDownloadingTheme( false );
		} )();
	}, [ wpAjaxUrl, downloadingTheme, savingOptions, selectedTheme, setError, themeSupport, updatesNonce ] );

	/**
	 * Fetches theme data when needed.
	 */
	useEffect( () => {
		if ( fetchingThemes || ! readerThemesEndpoint || themes || 'reader' !== themeSupport ) {
			return;
		}

		/**
		 * Fetch themes from the REST endpoint.
		 */
		( async () => {
			setFetchingThemes( true );

			try {
				const fetchedThemes = await apiFetch( { url: addQueryArgs( readerThemesEndpoint, { 'amp-new-onboarding': '1' } ) } );

				if ( hasUnmounted.current === true ) {
					return;
				}
github ampproject / amp-wp / assets / src / settings-page / index.js View on Github external
}
	}, [ didSaveOptions, downloadingTheme ] );

	/**
	 * If the success notice is showing and updates have been made, hide the notice.
	 */
	useEffect( () => {
		if ( 'visible' === savedNoticeClass && hasOptionsChanges ) {
			setSavedNoticeClass( 'dismissed' );
		}
	}, [ savedNoticeClass, hasOptionsChanges ] );

	/**
	 * Hide the success notice after several seconds.
	 */
	useEffect( () => {
		if ( 'visible' === savedNoticeClass ) {
			const timeout = setTimeout( () => {
				setSavedNoticeClass( 'dismissed' );
			}, 9000 );

			return () => {
				clearTimeout( timeout );
			};
		}

		return () => undefined;
	}, [ savedNoticeClass ] );

	/**
	 * Scroll to the focused element on load or when it changes.
	 */
github WordPress / gutenberg / packages / components / src / image / index.native.js View on Github external
export function Image( { src, alt, style, ...additionalProps }, ref ) {
	const [ aspectRatio, setAspectRatio ] = useState();
	useEffect( () => {
		let didCancel = false;

		if ( src ) {
			RNImage.getSize( src, ( width, height ) => {
				if ( ! didCancel ) {
					setAspectRatio(width / height);
				}
			} );
		} else {
			setAspectRatio( undefined );
		}

		return () => {
			didCancel = true;
		}
	}, [ src ] );
github WordPress / gutenberg / packages / components / src / popover / index.js View on Github external
getAnchorRect,
			anchorRef,
			shouldAnchorIncludePadding
		);

		newAnchor = addBuffer(
			newAnchor,
			anchorVerticalBuffer,
			anchorHorizontalBuffer
		);

		if ( ! isShallowEqual( newAnchor, anchor ) ) {
			setAnchor( newAnchor );
		}
	};
	useEffect( refreshAnchorRect, [ anchorRect, getAnchorRect ] );
	useEffect( () => {
		if ( ! anchorRect ) {
			/*
			* There are sometimes we need to reposition or resize the popover that are not
			* handled by the resize/scroll window events (i.e. CSS changes in the layout
			* that changes the position of the anchor).
			*
			* For these situations, we refresh the popover every 0.5s
			*/
			const intervalHandle = setInterval( refreshAnchorRect, 500 );

			return () => clearInterval( intervalHandle );
		}
	}, [ anchorRect ] );

	useThrottledWindowScrollOrResize( refreshAnchorRect, contentRef );
github Automattic / wp-calypso / apps / full-site-editing / full-site-editing-plugin / full-site-editing / lib / site-options / use-previous.js View on Github external
export function usePrevious( value ) {
	const ref = useRef();

	useEffect( () => {
		ref.current = value;
	}, [ value ] );

	return ref.current;
}
github Automattic / vip-go-mu-plugins-built / jetpack / extensions / blocks / instagram-gallery / use-connect-instagram.js View on Github external
export default function useConnectInstagram( {
	accessToken,
	noticeOperations,
	selectedAccount,
	setAttributes,
	setImages,
	setSelectedAccount,
} ) {
	const [ isConnecting, setIsConnecting ] = useState( false );
	const [ isRequestingUserConnections, setIsRequestingConnections ] = useState( false );
	const [ userConnections, setUserConnections ] = useState( [] );

	useEffect( () => {
		if ( accessToken ) {
			return;
		}

		setIsRequestingConnections( true );
		apiFetch( { path: '/wpcom/v2/instagram-gallery/connections' } )
			.then( connections => {
				setIsRequestingConnections( false );
				setUserConnections( connections );
			} )
			.catch( () => {
				setIsRequestingConnections( false );
				setUserConnections( [] );
			} );
	}, [ accessToken ] );
github WordPress / gutenberg / packages / components / src / custom-gradient-picker / control-points.js View on Github external
}
	};

	const cleanEventListeners = () => {
		if (
			window && window.removeEventListener &&
			controlPointMoveState.current && controlPointMoveState.current.listenersActivated
		) {
			window.removeEventListener( 'mousemove', onMouseMove );
			window.removeEventListener( 'mouseup', cleanEventListeners );
			onStopControlPointChange();
			controlPointMoveState.current.listenersActivated = false;
		}
	};

	useEffect( () => {
		return () => {
			cleanEventListeners();
		};
	}, [] );

	return markerPoints.map(
		( point, index ) => (
			point && ignoreMarkerPosition !== point.positionValue && (
				 (
						 {
								if (