Home > database >  Uncaught TypeError: useSelector is not a function
Uncaught TypeError: useSelector is not a function

Time:01-23

When trying to run my React app, I am getting the following error in my browser console: Uncaught TypeError: useSelector is not a function. The code is compiling fine on VS Code.

Here the App.js code that is causing issues:

const BrowserRouter = require('react-router-dom');
const Navigate = require('react-router-dom');
const Routes = require ('react-router-dom');
const Route = require ('react-router-dom');
const HomePage = require ('scenes/homePage');
const LoginPage = require ('scenes/loginPage');
const ProfilePage = require ('scenes/ProfilePage');
const useMemo = require ('react');
const useSelector = require ('react-redux');
const CssBaseline = require ('@mui/material');
const ThemeProvider = require ('@mui/material');
const createTheme = require ('@mui/material/styles');
const themeSettings = require ('./theme');


function App() {
  const mode = useSelector((state) => state.mode);
  const theme = useMemo(() => createTheme(themeSettings(mode)), [mode]);
  const isAuth = Boolean(useSelector((state) => state.token));

  return (
    <div className="app">
      <BrowserRouter>
        <ThemeProvider theme={theme}>
          <CssBaseline />
          <Routes>
            <Route path="/" element={<LoginPage />} />
            <Route
              path="/home"
              element={isAuth ? <HomePage /> : <Navigate to="/" />}
            />
            <Route
              path="/profile/:userId"
              element={isAuth ? <ProfilePage /> : <Navigate to="/" />}
            />
          </Routes>
        </ThemeProvider>
      </BrowserRouter>
    </div>
  );
}

export default App;

Any help would be appreciated. Thanks

I first had a look at previous threads and tried the following:

  • I double checked and I am importing useSelector correctly, using: const useSelector = require ('react-redux');
  • I also checked that my react-redux is at the latest version.
  • I also checked the react-redux documentation to make sure the syntax was correct and it doesn't seem to be a syntax error

CodePudding user response:

useSelector isn't a default export from react-redux, it's a named export.

const { useSelector } = require('react-redux');

or you might need to use:

const ReactRedux = require('react-redux');
...
ReactRedux.useSelector((state) => state.token);

or just use regular imports

import { useSelector } from 'react-redux';
  • Related