How to use the @webiny/app/hooks/useHandler.useHandler function in @webiny/app

To help you get started, we’ve selected a few @webiny/app 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 webiny / webiny-js / packages / app-security / src / contexts / Security / Security.js View on Github external
const user = await getUser();
            setState({ loading: false });
            return user;
        }

        // Get user using default authentication query
        const { data } = await client.query({ query: GET_CURRENT_USER, fetchPolicy: "no-cache" });
        setState({ loading: false });
        return data.security.getCurrentUser.data;
    });

    /**
     * Should be called only by authentication plugin when it obtains
     * an `idToken` from the authentication provider.
     */
    const onIdToken = useHandler(null, () => async idToken => {
        setState({ checkingUser: true });
        const { token, user } = await loginUsingIdToken(idToken);
        setIdentity(user);
        setToken(token);
        setState({ user, checkingUser: false });
        props.onUser && props.onUser(user);
    });

    // Run authentication plugin hook
    const { getIdToken, renderAuthentication, logout: authLogout } = auth.securityProviderHook({
        onIdToken
    });

    const logout = useCallback(async () => {
        await authLogout();
        localStorage.remove(AUTH_TOKEN);
github webiny / webiny-js / packages / app-page-builder / src / editor / plugins / slate / block / TypographySelector.js View on Github external
const [showMenu, setShowMenu] = useState(false);
    const dropdown = useRef();
    const { theme } = usePageBuilder();

    useEffect(() => {
        if (showMenu) {
            // $FlowFixMe
            const domRect = dropdown.current.getBoundingClientRect();
            if (domRect.right > window.innerWidth) {
                // $FlowFixMe
                dropdown.current.style.left = window.innerWidth - domRect.right + "px";
            }
        }
    });

    const setBlock = useHandler(props, ({ editor, onChange }) => type => {
        editor.change(change => onChange(change.setBlocks(type)));
    });

    const onStateChange = useCallback(({ isOpen }) => setShowMenu(isOpen), []);

    const { editor } = props;

    let blockType = editor.value.blocks.first().type;
    const style = theme.typography[blockType] || theme.typography.paragraph;

    return (
        
            {({ isOpen, getToggleButtonProps, getItemProps, highlightedIndex, selectedItem }) => (
                <div>
                    <button>{style.label}</button>
                    {isOpen &amp;&amp; (</div>
github webiny / webiny-js / packages / app-security / src / contexts / Security / Security.js View on Github external
if (!res.error) {
            return res.data.security.loginUsingIdToken.data;
        }

        return { user: null, token: null };
    };

    const removeToken = useCallback(() => {
        localStorage.remove(AUTH_TOKEN);
    }, []);

    const setToken = useCallback((token: string) => {
        return localStorage.set(AUTH_TOKEN, token);
    }, []);

    const getUser = useHandler(props, ({ getUser }) => async () => {
        setState({ loading: true });

        if (getUser) {
            const user = await getUser();
            setState({ loading: false });
            return user;
        }

        // Get user using default authentication query
        const { data } = await client.query({ query: GET_CURRENT_USER, fetchPolicy: "no-cache" });
        setState({ loading: false });
        return data.security.getCurrentUser.data;
    });

    /**
     * Should be called only by authentication plugin when it obtains
github webiny / webiny-js / packages / app-security / src / contexts / Security / Security.js View on Github external
});

    // Run authentication plugin hook
    const { getIdToken, renderAuthentication, logout: authLogout } = auth.securityProviderHook({
        onIdToken
    });

    const logout = useCallback(async () => {
        await authLogout();
        localStorage.remove(AUTH_TOKEN);
    }, []);

    /**
     * Check if user is logged-in and update state accordingly.
     */
    const checkUser = useHandler(null, () => async () => {
        const idToken = await getIdToken();

        if (!idToken) {
            removeToken();
            setState({ checkingUser: false, user: null });
            return;
        }

        // If AUTH_TOKEN is not present -> login using idToken provided by authentication plugin
        if (!getToken()) {
            const { token, user } = await loginUsingIdToken(idToken);

            if (token) {
                setIdentity(user);
                setToken(token);
                setState({ user, checkingUser: false });
github webiny / webiny-js / packages / app-security / src / admin / views / Account.js View on Github external
`You must register a "security-authentication-provider" plugin to render Account form!`
        );
    }

    const { renderUserAccountForm } = auth;

    const [{ loading, user }, setState] = useReducer((prev, next) => ({ ...prev, ...next }), {
        loading: true,
        user: { data: {} }
    });

    const client = useApolloClient();
    const { showSnackbar } = useSnackbar();
    const security = useSecurity();

    const onSubmit = useHandler(null, () => async formData => {
        setState({ loading: true });
        const { data: response } = await client.mutate({
            mutation: UPDATE_CURRENT_USER,
            variables: { data: omit(formData, ["id"]) }
        });
        const { error } = response.security.updateCurrentUser;
        setState({ loading: false });
        if (error) {
            return showSnackbar(error.message, {
                actionText: "Close"
            });
        }

        security.refreshUser();
        showSnackbar("Account saved successfully!");
    });
github webiny / webiny-js / packages / app-mailchimp / src / admin / components / MailchimpElementAdvancedSettings.js View on Github external
const MailchimpElementAdvancedSettings = ({ Bind }: Object) => {
    const [loading, setLoading] = useState(false);
    const { showSnackbar } = useSnackbar();
    const client = useApolloClient();

    const submitApiKeyForm = useHandler({}, () => async ({ data = {}, settingsLists }) => {
        setLoading(true);
        const response = await client.mutate({
            mutation: settingsGql.mutation,
            variables: { data: { ...data, enabled: true } }
        });
        setLoading(false);
        const error = get(response, "data.mailchimp.updateSettings.error");
        if (error) {
            showSnackbar(error.message);
        } else {
            showSnackbar("Settings updated successfully.");
            settingsLists.refetch();
        }
    });

    return (
github webiny / webiny-js / packages / app-page-builder / src / render / plugins / elements / embeds / pinterest / PinterestEmbed.js View on Github external
export default (props: Object) =&gt; {
    const { url } = get(props.element, "data.source") || {};

    useEffect(() =&gt; {
        appendSDK(props).then(() =&gt; initEmbed(props));
    }, []);

    const renderEmbed = useHandler(props, ({ element }) =&gt; {
        return function renderEmbed() {
            const data = get(element, "data.source");
            return (
                <div id="{element.id}">
                    <a href="{data.url}" data-pin-width="{data.size" data-pin-do="embedPin">
                </a></div><a href="{data.url}" data-pin-width="{data.size" data-pin-do="embedPin">
            );
        };
    });

    return url ? renderEmbed() : null;
};</a>
github webiny / webiny-js / packages / app-page-builder / src / admin / views / Pages / Pages.js View on Github external
const [showCategoriesDialog, setCategoriesDialog] = useState(false);
    const client = useApolloClient();
    const { showSnackbar } = useSnackbar();
    const { history } = useReactRouter();

    const dataList = useDataList({
        query: LIST_PAGES,
        variables: {
            sort: { savedOn: -1 }
        }
    });

    const openDialog = useCallback(() => setCategoriesDialog(true), []);
    const closeDialog = useCallback(() => setCategoriesDialog(false), []);

    const createPageMutation = useHandler(props, () => async category => {
        try {
            setCreatingPage(true);
            const res = await client.mutate({
                mutation: CREATE_PAGE,
                variables: { category },
                refetchQueries: ["PbListPages"],
                awaitRefetchQueries: true
            });
            setCreatingPage(false);
            closeDialog();
            const { data } = res.data.pageBuilder.page;
            history.push(`/page-builder/editor/${data.id}`);
        } catch (e) {
            showSnackbar(e.message);
        }
    });
github webiny / webiny-js / packages / app-page-builder / src / admin / plugins / pageDetails / header / deletePage / DeletePage.js View on Github external
const { history } = useReactRouter();
    const { showDialog } = useDialog();

    const title = get(props, "pageDetails.page.title", "N/A");

    const { showConfirmation } = useConfirmationDialog({
        title: "Delete page",
        message: (
            <p>
                You are about to delete the entire page and all of its revisions! <br>
                Are you sure you want to permanently delete the page <strong>{title}</strong>?
            </p>
        )
    });

    const confirmDelete = useHandler(
        { ...props, showConfirmation },
        ({ pageDetails: { page }, showConfirmation }) =&gt; () =&gt; {
            showConfirmation(async () =&gt; {
                const { data: res } = await client.mutate({
                    mutation: DELETE_PAGE,
                    variables: { id: page.parent },
                    refetchQueries: ["PbListPages"]
                });

                const { error } = dot.get(res, "pageBuilder.deletePage");
                if (error) {
                    return showDialog(error.message, { title: "Could not delete page" });
                }

                showSnackbar(
                    <span></span>
github webiny / webiny-js / packages / app-page-builder / src / editor / plugins / elementSettings / useUpdateHandlers.js View on Github external
export default (props: Object) => {
    const updateSettings = useHandler(props, ({ element, updateElement, dataNamespace }) => {
        let historyUpdated = {};
        return (name: string, newValue: mixed, history = false) => {
            const propName = `${dataNamespace}.${name}`;

            let newElement = set(element, propName, newValue);

            if (!history) {
                updateElement({
                    element: newElement,
                    history,
                    merge: true
                });
                return;
            }

            if (historyUpdated[propName] !== newValue) {