Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can't use useLocation() in react-router 5

I made an simple taskshceduler with react router 5 and react redux and work fine still.

Now I try animating between different route with react-transition-group.

For this i need the useLocation that i can pass this result to the CSSTransition.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

So the TransitionGroup can sense it and remove the page from the DOM for the right time.

But if I only initialize useLoaction from react-router-dom >> const location = useLocation();

I get error

What is the problem and What is the solution?

Thank you

App.js

import { Fragment, useEffect, Suspense } from "react";
import { useSelector, useDispatch } from "react-redux";
import Notification from "./shared/UIElements/Notification";
import { sendCartData, fetchCartData } from "./store/cart-actions";
import Auth from "./Auth/page/Auth";
import TaskMain from "./tasks/page/TaskMain";
import TaskFilter from "./tasks/page/TaskFilter";
import MainNavigation from "./Layout/Navigation/MainNavigation";
import LoadingSpinner from "./shared/UIElements/LoadingSpinner";
import TransitionGroup from "react-transition-group/TransitionGroup";
import CSSTransition from "react-transition-group/CSSTransition";
import "../src/scss/styles.css";

import UpdateTask from "./tasks/page/UpdateTask";
import {
  BrowserRouter as Router,
  Route,
  Redirect,
  Switch,
  useLocation,
} from "react-router-dom";
import NewTask from "./tasks/page/NewTask";

let isInitial = true;

function App() {
  const dispatch = useDispatch();
  const cart = useSelector((state) => state.cart);
  const notification = useSelector((state) => state.ui.notification);
  const logged = useSelector((state) => state.cart.logged);
  //THIS IS THE PROBLEM ROW:
  const location = useLocation();
  useEffect(() => {
    dispatch(fetchCartData());
    console.log(`fetch usefeect`);
  }, [dispatch]);

  useEffect(() => {
    if (isInitial) {
      isInitial = false;
      return;
    }

    if (cart.changed) {
      dispatch(sendCartData(cart));
    }
  }, [cart, dispatch]);

  let routes;
  if (!logged) {
    routes = (
      <Switch>
        <Route path="/" exact>
          <Auth />
        </Route>
        <Redirect to="/" />
      </Switch>
    );
  } else {
    routes = (
      <Switch>
        <Route path="/" exact>
          <TaskMain />
        </Route>
        <Route path="/tasks/new" exact>
          <NewTask />
        </Route>
        <Route path="/tasks/update/:id" exact>
          <UpdateTask />
        </Route>
        <Route path="/items" exact>
          <TaskFilter />
        </Route>
        <Redirect to="/" />
      </Switch>
    );
  }

  return (
    <Router>
      <Fragment>
        {notification && (
          <Notification
            status={notification.status}
            title={notification.title}
            message={notification.message}
          />
        )}
        <MainNavigation />
        <TransitionGroup>
          <CSSTransition
          timeout={250}
          classNames='fade'
          >
            <Suspense
              fallback={
                <div className="center">
                  <LoadingSpinner></LoadingSpinner>
                </div>
              }
            >
              {routes}
            </Suspense>
          </CSSTransition>
        </TransitionGroup>
      </Fragment>
    </Router>
  );
}

export default App;

Error:

hooks.js:29 Uncaught TypeError: Cannot read properties of undefined (reading 'location')
    at useLocation (hooks.js:29:1)
    at App (App.js:32:1)
    at renderWithHooks (react-dom.development.js:14985:1)
    at mountIndeterminateComponent (react-dom.development.js:17811:1)
    at beginWork (react-dom.development.js:19049:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at beginWork$1 (react-dom.development.js:23964:1)
    at performUnitOfWork (react-dom.development.js:22776:1)
    at workLoopSync (react-dom.development.js:22707:1)
    at renderRootSync (react-dom.development.js:22670:1)
    at performSyncWorkOnRoot (react-dom.development.js:22293:1)
    at scheduleUpdateOnFiber (react-dom.development.js:21881:1)
    at updateContainer (react-dom.development.js:25482:1)
    at react-dom.development.js:26021:1
    at unbatchedUpdates (react-dom.development.js:22431:1)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:26020:1)
    at Object.render (react-dom.development.js:26103:1)
    at Module.<anonymous> (index.js:8:1)
    at Module../src/index.js (index.js:10:1)
    at __webpack_require__ (bootstrap:856:1)
    at fn (bootstrap:150:1)
    at Object.1 (UpdateTask.js:8:1)
    at __webpack_require__ (bootstrap:856:1)
    at checkDeferredModules (bootstrap:45:1)
    at Array.webpackJsonpCallback [as push] (bootstrap:32:1)
    at main.chunk.js:1:93
useLocation @ hooks.js:29
App @ App.js:32
renderWithHooks @ react-dom.development.js:14985
mountIndeterminateComponent @ react-dom.development.js:17811
beginWork @ react-dom.development.js:19049
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
beginWork$1 @ react-dom.development.js:23964
performUnitOfWork @ react-dom.development.js:22776
workLoopSync @ react-dom.development.js:22707
renderRootSync @ react-dom.development.js:22670
performSyncWorkOnRoot @ react-dom.development.js:22293
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
(anonymous) @ index.js:8
./src/index.js @ index.js:10
__webpack_require__ @ bootstrap:856
fn @ bootstrap:150
1 @ UpdateTask.js:8
__webpack_require__ @ bootstrap:856
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.chunk.js:1
index.js:1 The above error occurred in the <App> component:

    at App (http://localhost:3000/static/js/main.chunk.js:191:83)
    at Provider (http://localhost:3000/static/js/0.chunk.js:37458:20)

Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
console.<computed> @ index.js:1
logCapturedError @ react-dom.development.js:20085
update.callback @ react-dom.development.js:20118
callCallback @ react-dom.development.js:12318
commitUpdateQueue @ react-dom.development.js:12339
commitLifeCycles @ react-dom.development.js:20736
commitLayoutEffects @ react-dom.development.js:23426
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
commitRootImpl @ react-dom.development.js:23151
unstable_runWithPriority @ scheduler.development.js:468
runWithPriority$1 @ react-dom.development.js:11276
commitRoot @ react-dom.development.js:22990
performSyncWorkOnRoot @ react-dom.development.js:22329
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
(anonymous) @ index.js:8
./src/index.js @ index.js:10
__webpack_require__ @ bootstrap:856
fn @ bootstrap:150
1 @ UpdateTask.js:8
__webpack_require__ @ bootstrap:856
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.chunk.js:1
hooks.js:29 Uncaught TypeError: Cannot read properties of undefined (reading 'location')
    at useLocation (hooks.js:29:1)
    at App (App.js:32:1)
    at renderWithHooks (react-dom.development.js:14985:1)
    at mountIndeterminateComponent (react-dom.development.js:17811:1)
    at beginWork (react-dom.development.js:19049:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
    at invokeGuardedCallback (react-dom.development.js:4056:1)
    at beginWork$1 (react-dom.development.js:23964:1)
    at performUnitOfWork (react-dom.development.js:22776:1)
    at workLoopSync (react-dom.development.js:22707:1)
    at renderRootSync (react-dom.development.js:22670:1)
    at performSyncWorkOnRoot (react-dom.development.js:22293:1)
    at scheduleUpdateOnFiber (react-dom.development.js:21881:1)
    at updateContainer (react-dom.development.js:25482:1)
    at react-dom.development.js:26021:1
    at unbatchedUpdates (react-dom.development.js:22431:1)
    at legacyRenderSubtreeIntoContainer (react-dom.development.js:26020:1)
    at Object.render (react-dom.development.js:26103:1)
    at Module.<anonymous> (index.js:8:1)
    at Module../src/index.js (index.js:10:1)
    at __webpack_require__ (bootstrap:856:1)
    at fn (bootstrap:150:1)
    at Object.1 (UpdateTask.js:8:1)
    at __webpack_require__ (bootstrap:856:1)
    at checkDeferredModules (bootstrap:45:1)
    at Array.webpackJsonpCallback [as push] (bootstrap:32:1)
    at main.chunk.js:1:93
useLocation @ hooks.js:29
App @ App.js:32
renderWithHooks @ react-dom.development.js:14985
mountIndeterminateComponent @ react-dom.development.js:17811
beginWork @ react-dom.development.js:19049
callCallback @ react-dom.development.js:3945
invokeGuardedCallbackDev @ react-dom.development.js:3994
invokeGuardedCallback @ react-dom.development.js:4056
beginWork$1 @ react-dom.development.js:23964
performUnitOfWork @ react-dom.development.js:22776
workLoopSync @ react-dom.development.js:22707
renderRootSync @ react-dom.development.js:22670
performSyncWorkOnRoot @ react-dom.development.js:22293
scheduleUpdateOnFiber @ react-dom.development.js:21881
updateContainer @ react-dom.development.js:25482
(anonymous) @ react-dom.development.js:26021
unbatchedUpdates @ react-dom.development.js:22431
legacyRenderSubtreeIntoContainer @ react-dom.development.js:26020
render @ react-dom.development.js:26103
(anonymous) @ index.js:8
./src/index.js @ index.js:10
__webpack_require__ @ bootstrap:856
fn @ bootstrap:150
1 @ UpdateTask.js:8
__webpack_require__ @ bootstrap:856
checkDeferredModules @ bootstrap:45
webpackJsonpCallback @ bootstrap:32
(anonymous) @ main.chunk.js:1
DevTools failed to load source map: Could not load content for chrome-extension://gpaiobkfhnonedkhhfjpmhdalgeoebfa/editor/config.js.map: System error: net::ERR_BLOCKED_BY_CLIENT
DevTools failed to load source map: Could not load content for chrome-extension://gpaiobkfhnonedkhhfjpmhdalgeoebfa/editor/content.js.map: System error: net::ERR_BLOCKED_BY_CLIENT
DevTools failed to load source map: Could not load content for chrome-extension://gpaiobkfhnonedkhhfjpmhdalgeoebfa/editor/config.js.map: System error: net::ERR_BLOCKED_BY_CLIENT
DevTools failed to load source map: Could not load content for chrome-extension://gpaiobkfhnonedkhhfjpmhdalgeoebfa/editor/content.js.map: System error: net::ERR_BLOCKED_BY_CLIENT
VM173:2 Uncaught ReferenceError: process is not defined
    at Object.4043 (<anonymous>:2:13168)
    at r (<anonymous>:2:306599)
    at Object.8048 (<anonymous>:2:9496)
    at r (<anonymous>:2:306599)
    at Object.8641 (<anonymous>:2:1379)
    at r (<anonymous>:2:306599)
    at <anonymous>:2:315627
    at <anonymous>:2:324225
    at <anonymous>:2:324229
    at HTMLIFrameElement.e.onload (index.js:1:1)

Package.json dependencies:

"dependencies": {
    "@reduxjs/toolkit": "^1.5.0",
    "@testing-library/jest-dom": "^5.11.6",
    "@testing-library/react": "^11.2.2",
    "@testing-library/user-event": "^12.5.0",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-redux": "^7.2.2",
    "react-router-dom": "5.3.0",
    "react-scripts": "4.0.1",
    "react-spring": "^9.4.3",
    "react-transition-group": "^4.4.2",
    "use-sound": "^4.0.1",
    "uuidv4": "^6.2.12",
    "web-vitals": "^0.2.4"
  },

>Solution :

Seems like you’re trying to use router context outside of Router. You should separate components, so useLocation will be used only in component, that is nested to Router.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading