How to navigate to other page when location.state is null - javascript

I have a react application where I pass state via react router and access the state using location in the target component/page. It works perfect, however when I close the tab and paste the exact same url to that page in another tab it crashes and says Cannot read properties of null (reading '1'). This is how I am accessing the state:
const { filter, mode } = location?.state[1];
I want to navigate to home page if the location state is null.
I have tried the following but does not seem to work.
if (location.state === null) {
navigate("/");
}
const { filter, mode } = location?.state[1];
Any help will be appreciated

The code is still running after navigate if you don't return
if (location.state===null) {
navigate("/");
return null;
}
const { filter, mode } = location?.state[1];

You will need to split the logic between issuing the imperative navigation action as a side-effect, and returning null from the component so you are not accidentally accessing null or undefined state.
Example:
useEffect(() => {
if (location.state === null) {
navigate("/");
}
}, []);
const { filter, mode } = location?.state[1];
if (!location.state) {
return null;
}
Alternatively you could simply return the Navigate component instead. Just ensure that any and all React hooks are unconditionally called prior to any early returns from the React function body.
Example:
...
if (location.state === null) {
return <Navigate to="/" />;
}
const { filter, mode } = location?.state[1];

Related

localStorage resets to empty on refresh in NextJS

I have a shopping cart system in my next.js app using Context.
I define my cart with useState:
const [cartItems, setCartItems] = useState([]);
Then I use useEffect to check and update the localStorage:
useEffect(() => {
if (JSON.parse(localStorage.getItem("cartItems"))) {
const storedCartItems = JSON.parse(localStorage.getItem("cartItems"));
setCartItems([...cartItems, ...storedCartItems]);
}
}, []);
useEffect(() => {
window.localStorage.setItem("cartItems", JSON.stringify(cartItems));
}, [cartItems]);
This stores the items in localStorage fine, but when I refresh, it resets the cartItems item in localStorage to an empty array. I've seen a few answers where you get the localStorage item before setting the cart state but that throws localStorage is not defined errors in Next. How can I do this?
setCartItems sets the value of cartItems for the next render, so on the initial render it's [] during the second useEffect
You can fix this by storing a ref (which doesn't rerender on state change) for whether it's the first render or not.
import React, { useState, useRef } from "react";
// ...
// in component
const initialRender = useRef(true);
useEffect(() => {
if (JSON.parse(localStorage.getItem("cartItems"))) {
const storedCartItems = JSON.parse(localStorage.getItem("cartItems"));
setCartItems([...cartItems, ...storedCartItems]);
}
}, []);
useEffect(() => {
if (initialRender.current) {
initialRender.current = false;
return;
}
window.localStorage.setItem("cartItems", JSON.stringify(cartItems));
}, [cartItems]);
React never updates state immediately It's an asynchronous process, for example, if you console.log(stateValue) just after the setState() method you'll get prevState value in a log. You can read more about it here.
That is exactly happening here, you have called setState method inside the first useEffect, state has not updated yet by react and we're trying to update localStorage with the latest state value(for now it's [] since react has not updated the state yet). that's why the localStorage value holds an empty array.
For your case, you can skip the first execution of 2nd useEffect as #Samathingamajig's mentioned in his answer.
PS: Thanks #Samathingamajig for pointing out the silly mistake, I don't know how missed that. LOL
thanks to jamesmosier for his answer on gitHub
The issue you are seeing is because localStorage (aka window.localStorage) is not defined on the server side. Next server renders your components, so when that happens and it tried to access localStorage it can't find it. You'll have to wait until the browser renders it in order to use localStorage.
full answer link here
EDIT
you can try this :
useEffect(() => {
if (typeof window !== "undefined") {
const storedCartItems = JSON.parse(localStorage.getItem("cartItems"));
if(storedCartItems !== null) {
setCartItems([...cartItems, ...storedCartItems]);
}
}
}, []);
useEffect(() => {
if (typeof window !== "undefined") {
window.localStorage.setItem("cartItems", JSON.stringify(cartItems));
}
}, [cartItems]);

How to prevent state updates from a function, running an async call

so i have a bit of a weird problem i dont know how to solve.
In my code i have a custom hook with a bunch of functionality for a fetching a list
of train journeys. I have some useEffects to that keeps loading in new journeys untill the last journey of the day.
When i change route, while it is still loading in new journeys. I get the "changes to unmounted component" React error.
I understand that i get this error because the component is doing an async fetch that finishes after i've gone to a new page.
The problem i can't figure out is HOW do i prevent it from doing that? the "unmounted" error always occur on one of the 4 lines listed in the code snippet.
Mock of the code:
const [loading, setLoading] = useState(true);
const [journeys, setJourneys] = useState([]);
const [hasLaterDepartures, setHasLaterDepartures] = useState(true);
const getJourneys = async (date, journeys) => {
setLoading(true);
setHasLaterDepartures(true);
const selectedDateJourneys = await fetchJourney(date); // Fetch that returns 0-3 journeys
if (condition1) setHasLaterDepartures(false); // trying to update unmounted component
if (condition2) {
if (condition3) {
setJourneys(something1); // trying to update unmounted component
} else {
setJourneys(something2) // trying to update unmounted component
}
} else {
setJourneys(something3); // trying to update unmounted component
}
};
// useEffects for continous loading of journeys.
useEffect(() => {
if (!hasLaterDepartures) setLoading(false);
}, [hasLaterDepartures]);
useEffect(() => {
if (hasLaterDepartures && journeys.length > 0) {
const latestStart = ... // just a date
if (latestStart.addMinutes(5).isSameDay(latestStart)) {
getJourneys(latestStart.addMinutes(5), journeys);
} else {
setLoading(false);
}
}
}, [journeys]);
I can't use a variable like isMounted = true in the useEffect beacuse it would reach inside the if statement and reach a "setState" by the time i'm on another page.
Moving the entire call into a useEffect doesn't seem to work either. I am at a loss.
Create a variable called mounted with useRef, initialised as true. Then add an effect to set mounted.current to false when the component unmounts.
You can use mounted.current anywhere inside the component to see if it's mounted, and check that before setting any state.
useRef gives you a variable you can mutate but which doesn't cause a rerender.
When you use useEffect hook with action which can be done after component change you should also take care about clean effect when needed. Maybe example help you, also check this page.
useEffect(() => {
let isClosed = false
const fetchData = async () => {
const data = await response.json()
if ( !isClosed ) {
setState( data )
}
};
fetchData()
return () => {
isClosed = true
};
}, []);
In your use case, you probably want to create a Store that doesn't reload everytime you change route (client side).
Example of a store using useContext();
const MyStoreContext = createContext()
export function useMyStore() {
const context = useContext(MyStoreContext)
if (!context && typeof window !== 'undefined') {
throw new Error(`useMyStore must be used within a MyStoreContext`)
}
return context
}
export function MyStoreProvider(props) {
const [ myState, setMyState ] = useState()
//....whatever codes u doing with ur hook.
const exampleCustomFunction = () => {
return myState
}
const getAllRoutes = async (mydestination) => {
return await getAllMyRoutesFromApi(mydestination)
}
// you return all your "getter" and "setter" in value props so you can use them outside the store.
return <MyStoreContext.Provider value={{ myState, setMyState, exampleCustomFunction, getAllRoutes }}>{props.children}</MyStoreContext.Provider>
}
You will wrap the store around your entire App, e.g.
<MyStoreProvider>
<App />
</MyStoreProvider>
In your page where you want to use your hook, you can do
const { myState, setMyState, exampleCustomFunction, getAllRoutes } = useMyStore()
const onClick = async () => getAllRouters(mydestination)
Considering if you have client side routing (not server side), this doesn't get reloaded every time you change your route.

React Router Navbar depending on route

I am trying to style a Navbar Link depending on the current path in my React App, if the path is /create or /add it should change it's styling. Here is what I have so far in my header component:
<div
id="createLink"
className={this.state.createClassName}
onClick={() => this.handleModalToggle()}
>
CREATE
</div>
handleActiveLink= () => {
let path = this.props.location.pathname
if (path === "/add" | path === "/create") {
this.setState({createClassName: "nav-link-active"})
} else {
this.setState({ createClassName: "nav-link" })
}
};
componentDidMount() {
this.handleActiveLink()
}
This works but only after I refresh the page which makes sense but it's not what I want. So I am looking for a way to change the className before even rendered and get the path first (I am using withRouter from react-router-dom)
Issue appears to be you only check the path when the component mounts and not when it updates. You should also check in componentDidUpdate
handleActiveLink= () => {
let path = this.props.location.pathname;
if (path === "/add" || path === "/create") {
this.setState({createClassName: "nav-link-active"});
} else {
this.setState({ createClassName: "nav-link" });
}
};
componentDidMount() {
this.handleActiveLink();
}
componentDidUpdate() {
this.handleActiveLink();
}
In this case I instead recommend not storing such transient data in state, and simply derive it from the props and set as a className in the render function (or wherever you render it). This way it's computed each render when the UI is going to be updated by something and will always be up-to-date (i.e. you won't need to worry about lifecycle functions).
render() {
const { location: { pathname } } = this.props;
const linkClass = ["/add", "/create"].includes(pathname)
? "nav-link-active"
: "nav-link";
...
<div
id="createLink"
className={linkClass}
onClick={() => this.handleModalToggle()}
>
CREATE
</div>
...
}

useEffect does not listen for localStorage

I'm making an authentication system and after backend redirects me to the frontend page I'm making API request for userData and I'm saving that data to localStorage. Then I'm trying to load Spinner or UserInfo.
I'm trying to listen for the localStorage value with useEffect, but after login I'm getting 'undefined'. When the localStorage value is updated useEffect does not run again and Spinner keeps spinning forever.
I have tried to do: JSON.parse(localStorage.getItem('userData')), but then I got a useEffect infinite loop.
Only when I'm refreshing the page does my localStorage value appear and I can display it instead of Spinner.
What I'm doing wrong?
Maybe there is a better way to load userData when it's ready?
I'm trying to update DOM in correct way?
Thanks for answers ;)
import React, { useState, useEffect } from 'react';
import { Spinner } from '../../atoms';
import { Navbar } from '../../organisms/';
import { getUserData } from '../../../helpers/functions';
const Main = () => {
const [userData, setUserData] = useState();
useEffect(() => {
setUserData(localStorage.getItem('userData'));
}, [localStorage.getItem('userData')]);
return <>{userData ? <Navbar /> : <Spinner />}</>;
};
export default Main;
It would be better to add an event listener for localstorage here.
useEffect(() => {
function checkUserData() {
const item = localStorage.getItem('userData')
if (item) {
setUserData(item)
}
}
window.addEventListener('storage', checkUserData)
return () => {
window.removeEventListener('storage', checkUserData)
}
}, [])
Event listener to 'storage' event won't work in the same page
The storage event of the Window interface fires when a storage area
(localStorage) has been modified in the context of another document.
https://developer.mozilla.org/en-US/docs/Web/API/Window/storage_event
The solution is to use this structure:
useEffect(() => {
window.addEventListener("storage", () => {
// When storage changes refetch
refetch();
});
return () => {
// When the component unmounts remove the event listener
window.removeEventListener("storage");
};
}, []);
"Maybe there is a better way to load userData when it's ready?"
You could evaluate the value into localStorage directly instead passing to state.
const Main = () => {
if (localStage.getItem('userData')) {
return (<Navbar />);
}
else {
return (<Spinner />);
}
};
If there is a need to retrieve the userData in more components, evaluate the implementation of Redux to your application, this could eliminate the usage of localStorage, but of course, depends of your needs.

Intercept/handle browser's back button in React-router?

I'm using Material-ui's Tabs, which are controlled and I'm using them for (React-router) Links like this:
<Tab value={0} label="dashboard" containerElement={<Link to="/dashboard/home"/>}/>
<Tab value={1} label="users" containerElement={<Link to="/dashboard/users"/>} />
<Tab value={2} label="data" containerElement={<Link to="/dashboard/data"/>} />
If I'm currenlty visting dashboard/data and I click browser's back button
I go (for example) to dashboard/users but the highlighted Tab still stays on dashboard/data (value=2)
I can change by setting state, but I don't know how to handle the event when the browser's back button is pressed?
I've found this:
window.onpopstate = this.onBackButtonEvent;
but this is called each time state is changed (not only on back button event)
Using react-router made the job simple as such:
import { browserHistory } from 'react-router';
componentDidMount() {
this.onScrollNearBottom(this.scrollToLoad);
this.backListener = browserHistory.listen((loc, action) => {
if (action === "POP") {
// Do your stuff
}
});
}
componentWillUnmount() {
// Unbind listener
this.backListener();
}
Using hooks you can detect the back and forward buttons
import { useHistory } from 'react-router-dom'
const [ locationKeys, setLocationKeys ] = useState([])
const history = useHistory()
useEffect(() => {
return history.listen(location => {
if (history.action === 'PUSH') {
setLocationKeys([ location.key ])
}
if (history.action === 'POP') {
if (locationKeys[1] === location.key) {
setLocationKeys(([ _, ...keys ]) => keys)
// Handle forward event
} else {
setLocationKeys((keys) => [ location.key, ...keys ])
// Handle back event
}
}
})
}, [ locationKeys, ])
here is how I ended up doing it:
componentDidMount() {
this._isMounted = true;
window.onpopstate = ()=> {
if(this._isMounted) {
const { hash } = location;
if(hash.indexOf('home')>-1 && this.state.value!==0)
this.setState({value: 0})
if(hash.indexOf('users')>-1 && this.state.value!==1)
this.setState({value: 1})
if(hash.indexOf('data')>-1 && this.state.value!==2)
this.setState({value: 2})
}
}
}
thanks everybody for helping lol
Hooks sample
const {history} = useRouter();
useEffect(() => {
return () => {
// && history.location.pathname === "any specific path")
if (history.action === "POP") {
history.replace(history.location.pathname, /* the new state */);
}
};
}, [history])
I don't use history.listen because it doesn't affect the state
const disposeListener = history.listen(navData => {
if (navData.pathname === "/props") {
navData.state = /* the new state */;
}
});
Most of the answers for this question either use outdated versions of React Router, rely on less-modern Class Components, or are confusing; and none use Typescript, which is a common combination. Here is an answer using Router v5, function components, and Typescript:
// use destructuring to access the history property of the ReactComponentProps type
function MyComponent( { history }: ReactComponentProps) {
// use useEffect to access lifecycle methods, as componentDidMount etc. are not available on function components.
useEffect(() => {
return () => {
if (history.action === "POP") {
// Code here will run when back button fires. Note that it's after the `return` for useEffect's callback; code before the return will fire after the page mounts, code after when it is about to unmount.
}
}
})
}
A fuller example with explanations can be found here.
Version 3.x of the React Router API has a set of utilities you can use to expose a "Back" button event before the event registers with the browser's history. You must first wrap your component in the withRouter() higher-order component. You can then use the setRouteLeaveHook() function, which accepts any route object with a valid path property and a callback function.
import {Component} from 'react';
import {withRouter} from 'react-router';
class Foo extends Component {
componentDidMount() {
this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave);
}
routerWillLeave(nextState) { // return false to block navigation, true to allow
if (nextState.action === 'POP') {
// handle "Back" button clicks here
}
}
}
export default withRouter(Foo);
Using hooks. I have converted #Nicolas Keller's code to typescript
const [locationKeys, setLocationKeys] = useState<(string | undefined)[]>([]);
const history = useHistory();
useEffect(() => {
return history.listen((location) => {
if (history.action === 'PUSH') {
if (location.key) setLocationKeys([location.key]);
}
if (history.action === 'POP') {
if (locationKeys[1] === location.key) {
setLocationKeys(([_, ...keys]) => keys);
// Handle forward event
console.log('forward button');
} else {
setLocationKeys((keys) => [location.key, ...keys]);
// Handle back event
console.log('back button');
removeTask();
}
}
});
}, [locationKeys]);
I used withrouter hoc in order to get history prop and just write a componentDidMount() method:
componentDidMount() {
if (this.props.history.action === "POP") {
// custom back button implementation
}
}
in NextJs we can use beforePopState function and do what we want such close modal or show a modal or check the back address and decide what to do
const router = useRouter();
useEffect(() => {
router.beforePopState(({ url, as, options }) => {
// I only want to allow these two routes!
if (as === '/' ) {
// Have SSR render bad routes as a 404.
window.location.href = as;
closeModal();
return false
}
return true
})
}, [])
For giving warning on the press of browser back in react functional components. do the following steps
declare isBackButtonClicked and initialize it as false and maintain the state using setBackbuttonPress function.
const [isBackButtonClicked, setBackbuttonPress] = useState(false);
In componentdidmount, add the following lines of code
window.history.pushState(null, null, window.location.pathname);
window.addEventListener('popstate', onBackButtonEvent);
define onBackButtonEvent Function and write logic as per your requirement.
const onBackButtonEvent = (e) => {
e.preventDefault();
if (!isBackButtonClicked) {
if (window.confirm("Do you want to go to Test Listing")) {
setBackbuttonPress(true)
props.history.go(listingpage)
} else {
window.history.pushState(null, null, window.location.pathname);
setBackbuttonPress(false)
}
}
}
In componentwillmount unsubscribe onBackButtonEvent Function
Final code will look like this
import React,{useEffect,useState} from 'react'
function HandleBrowserBackButton() {
const [isBackButtonClicked, setBackbuttonPress] = useState(false)
useEffect(() => {
window.history.pushState(null, null, window.location.pathname);
window.addEventListener('popstate', onBackButtonEvent);
//logic for showing popup warning on page refresh
window.onbeforeunload = function () {
return "Data will be lost if you leave the page, are you sure?";
};
return () => {
window.removeEventListener('popstate', onBackButtonEvent);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
const onBackButtonEvent = (e) => {
e.preventDefault();
if (!isBackButtonClicked) {
if (window.confirm("Do you want to go to Test Listing")) {
setBackbuttonPress(true)
props.history.go(listingpage)
} else {
window.history.pushState(null, null, window.location.pathname);
setBackbuttonPress(false)
}
}
}
return (
<div>
</div>
)
}
export default HandleBrowserBackButton
If you are using React Router V5, you can try Prompt.
Used to prompt the user before navigating away from a page. When your application enters a state that should prevent the user from navigating away (like a form is half-filled out), render a <Prompt>
<Prompt
message={(location, action) => {
if (action === 'POP') {
console.log("Backing up...")
// Add your back logic here
}
return true;
}}
/>
just put in componentDidMount()
componentDidMount() {
window.onbeforeunload =this.beforeUnloadListener;
}
beforeUnloadListener = (event) => {
event.preventDefault();
return event.returnValue = "Are you sure you want to exit?";
};
Add these 2 lines in to your componentDidMount().This worked for me
window.history.pushState(null, null, document.URL);
window.addEventListener('popstate', function(event) {
window.location.replace(
`YOUR URL`
);
});
It depends on the type of Router you use in React.
If you use BrowserRouter from react-router (not available in react-router v4 though), as mentioned above, you can use the action 'POP' to intercept the browser back button.
However, if you use HashRouter to push the routes, above solution will not work. The reason is hash router always triggered with 'POP' action when you click browser back button or pushing the route from your components. You cant differentiate these two actions either with window.popstate or history.listen simply.
Upcoming version 6.0 introduces useBlocker hook - which could be used to intercept all navigation attempts.
import { Action } from 'history';
import { useBlocker } from 'react-router';
// when blocker should be active
const unsavedChanges = true;
useBlocker((transition) => {
const {
location, // The new location
action, // The action that triggered the change
} = transition;
// intercept back and forward actions:
if (action === Action.Pop) {
alert('intercepted!')
}
}, unsavedChanges);
You can use "withrouter" HOC and use this.props.history.goBack.
<Button onClick={this.props.history.goBack}>
BACK
</Button>

Categories

Resources