Quantcast
Channel: Ionic Framework - Ionic Forum
Viewing all articles
Browse latest Browse all 48979

[Ionic React] Functional component do not get correct location from useLocation hook

$
0
0

Hello there,

I’m facing to an issue which I do not understand.
I created a functional component, and use the hook useLocation from react-router.

If I print the location on a mobile device, I always get the root url /
From computer browser, the location is correct.

Did you already see this problem ?
If I transform my functional component to a class, and use componentDidMount with the withRouter method, it works as expected.
But why there is this problem with FC ?

Thank you in advance for any hint !

Here is my code :

import React, {useEffect} from "react";
import {Network} from "@capacitor/network";
import {useIonAlert} from "@ionic/react";
import {useTranslation} from "react-i18next";
import {useHistory, useLocation} from "react-router";
import {routesUrl} from "../routes/Routes";

const AppNetworkListener: React.FunctionComponent = (props) => {
    const {t} = useTranslation();
    const history = useHistory();
    const location = useLocation();

    const [showNetworkError, hideNetworkError] = useIonAlert();

    // Mimic componentDidMount
    useEffect(() => {
        // Listen for network change
        Network.addListener('networkStatusChange', status => {
            if (status.connected) {
                console.debug(location.pathname, routesUrl.scanner)
                hideNetworkError();
            } else {
                showError()
            }
        });

        // On application load see if the network is available
        Network.getStatus().then(state => {
            if (!state.connected) {
                showError()
            }
        });
    }, []);

    const showError = (): void => {
        showNetworkError({
            cssClass: 'error-alert',
            backdropDismiss: false,
            header: t('notifications.network_error.header'),
            message: t('notifications.network_error.message')
        });

        // If user is stuck on scanner page redirect it, avoid to continue scanning and getting errors
        // Todo detection of pathname on DEVICE is not correct ! Always return / with functional component, may change this as class and use componentDidMount
        console.debug(location.pathname, routesUrl.scanner)
        if (location.pathname === routesUrl.scanner) {
            history.goBack();
        }
    }

    return null;
}

export default AppNetworkListener

1 post - 1 participant

Read full topic


Viewing all articles
Browse latest Browse all 48979

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>