nextjs router.events.on not called on intial page load - reactjs

I have a working useEffect to call my google analytics when changing page.
This works fine when changing pages but when you initially load for the first time or refresh it does not call the router.events.on
this is my code
useEffect(() => {
if (cookies === true) {
router.events.on("routeChangeComplete", () => {
ReactGA.pageview(window.location.pathname);
});
return () => {
router.events.off("routeChangeComplete", () => {
ReactGA.pageview(window.location.pathname);
});
};
}
}, [router.events]);
I thought of using an other useEffect to initially call the reactGA but then when changing page it would be called twice, which is not good.
any idea on how to make this work on the initial page load?

That's expected behaviour - router.events is only triggered on client-side page navigations initiated by the Next.js router.
You can call ReactGA.pageview on a separate useEffect to handle initial page loads.
useEffect(() => {
if (cookies === true) {
ReactGA.pageview(window.location.pathname);
}
}, []);

Related

React Render UI Before Redirect

I am having problem rendering ui before redirect in react. I has a variable is called from api, i want to check if it is 'x' then will redirect. But ui will render before redirect.
Bellow is my code:
useLayoutEffect(() => {
getProfile().then((res) => {
setIsLoading(true);
if (res) {
redirectByUserType(res.data.type); // redirect to /home
}
});
}, []);
I tried using useLayoutEffect but not working.
Please help me, thank you so much.
If you don't want to render until getProfile() has finished, then have a state variable which tracks whether it is finished. If it hasn't finished, return null to render nothing. If it has, return whatever you want to render. I would normally call this state variable loading, but you seem to already have one with that name, who's purpose i don't know. Maybe you can piggy back on that, maybe you need a separate one:
const [ready, setReady] = useState(false);
useEffect(() => {
getProfile().then(res => {
setIsLoading(true);
if(res) {
redirectByUserType(res.data.type);
} else {
setReady(true)
}
});
}, []);
if (!ready) {
return null;
}
return (
<div>Something</div>
);

Best way to detect if a user leaves the page in React (i.e. refresh, close tab, or change url) [duplicate]

I want a function, to send a request to a server (don't care about response) before a user refreshes the page.
I've tried using the componentWillUnmount approach but the page refresh doesn't call this function. e.g.
import React, { useEffect } from 'react';
const ComponentExample => () => {
useEffect(() => {
return () => {
// componentWillUnmount in functional component.
// Anything in here is fired on component unmount.
// Call my server to do some work
}
}, []) }
Does anyone have any ideas how to do this?
You could try listening for the window.beforeunload event.
The beforeunload event is fired when the window, the document and its
resources are about to be unloaded. The document is still visible and
the event is still cancelable at this point.
useEffect(() => {
const unloadCallback = (event) => { ... };
window.addEventListener("beforeunload", unloadCallback);
return () => window.removeEventListener("beforeunload", unloadCallback);
}, []);
Note: This will respond to anything that causes the page to unload though.
Note 2:
However note that not all browsers support this method, and some
instead require the event handler to implement one of two legacy
methods:
assigning a string to the event's returnValue property
returning a string from the event handler.
You can do this, almost, by checking if the page has been refreshed.
Source: https://developer.mozilla.org/en-US/docs/Web/API/Navigation_timing_API
Example:
if (window.performance) {
console.info("window.performance is supported");
console.info(performance.navigation.type);
if (performance.navigation.type == performance.navigation.TYPE_RELOAD) {
console.info( "This page is reloaded" );
} else {
console.info( "This page is not reloaded");
}
}

Undefined redux props when refresh page in react

I'm having trouble getting datas from redux when I refresh my page
const [filters, setFilters] = useState<string[]>(props.filters);
useEffect(() => {
(() => {
if (!_.isEqual(filters, props.filters)) {
setFilters(props.filters);
}
})();
});
My filters are undefined even though when I check redux devtools, there is datas in filters.
I need to trigger an event in my front to display my filters.
Anyone have an idea please ?
Edit:
(if I click any element in my page it load my filters)
If I add a setTimeout on refresh it works but I'm not sure using setTimeout is a solution
useEffect(() => {
setTimeout(() => {
setFilters(props.filters);
}, 1500);
}, []);
May be you just missed returning the inner functions:
Or just call the setFilters like:
useEffect(() => {
if (!_.isEqual(filters, props.filters)) {
setFilters(props.filters);
}
});

How to have a loading icon between react router route transitions?

Trying to get the preloader to show, fade out, and then show the new route. How to do this? Right now the page is flashing, then the preloader shows, and fades out to the new route.
I'm trying to use useLocation with useEffect(() => {...}, [location]) but it's causing the flash.
At the router level I have it add a loading class to the body so the preloader shows. Once the route component is mounted I'm removing that class. It seems like the useEffect that triggers on location change is getting called after the route render though.
Alright so this seems to have fixed it here is the code I had before.
useEffect(() => {
document.body.classList.remove('loaded');
window.scrollTo(0, 0);
const currentPath = location.pathname + location.search;
analytics.sendPageview(currentPath);
setTimeout(function () {
document.body.classList.add("loaded");
}, 1000);
}, [location]);
Here is the code I switched to that fixed it.
useEffect(() => {
return history.listen(location => {
document.body.classList.remove('loaded');
setTimeout(function () {
document.body.classList.add("loaded");
}, 1000);
})
}, [history])

how to load a function when a page load react native

I'm using react-native with hooks, and I'm trying to load a JSON from AsyncStorage every time a user opens one of my react-native screens This JSON contains information on what my states should be set to.
How can I call a function that runs every time this screen is opened?
i know that without hooks this should be done with useEffect, but when i put my api call there it makes an error
this is my code
useEffect(() => {
const getKind = () => {
ForceApi.post(`/GetKindPensionController.php`)
.then(res => {
setpPensionKind(res.data.pension);
})
}
}, []);
You are missing call the getKind, and it should be a async function! For a better code try something like:
useEffect(() => {
async function getKind() {
const { data } = await ForceApi.post(`/GetKindPensionController.php`)
setpPensionKind(data.pension);
}
getKind();
}, []);

Resources