0

To start learning React I've set up a project but while making the Login functionality I run into the following issue:

The error:

What I'm trying to accomplish is that when a user is logged in, he is returned to the previous page. The rest of my functionality is working but it's just the fact dat the 'State' property in fact does not exist.

Any ideas?

Package.json

Edit:

I'm following this tutorial: https://ui.docs.amplify.aws/react/guides/auth-protected

Login:

import { useEffect } from "react";

import { Authenticator, useAuthenticator, View } from '@aws-amplify/ui-react';
import '@aws-amplify/ui-react/styles.css';

import { useNavigate, useLocation } from 'react-router';

export function Login() {
  const { route } = useAuthenticator((context) => [context.route]);
  const location = useLocation();
  const navigate = useNavigate();
  let from = location.state?.from?.pathname || '/';
  useEffect(() => {
    if (route === 'authenticated') {
      navigate(from, { replace: true });
    }
  }, [route, navigate, from]);
  return (
    <View className="auth-wrapper">
      <Authenticator></Authenticator>
    </View>
  );
}

Index.js:

import * as React from 'react';
import * as ReactDOM from 'react-dom/client';
import './index.css';
import reportWebVitals from './reportWebVitals';
import {BrowserRouter, Routes, Route, useLocation } from "react-router-dom";
import { ThemeProvider, createTheme, responsiveFontSizes } from '@mui/material/styles';
import CssBaseline from '@mui/material/CssBaseline';
import Container from '@mui/material/Container';
import awsExports from './aws-exports';
import { Authenticator } from '@aws-amplify/ui-react';
import { Amplify } from 'aws-amplify';


import { App } from './App';
import { Login } from './components/authentication/Login';
import SignOut from './components/authentication/Logout';
import { Banner } from './components/home/Banner';
import { Test } from './components/Test';
import { RequireAuth } from './components/authentication/RequireAuth'

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);

let darkTheme = createTheme({
  palette: {
    mode: 'dark',
  },
  components: {
    MuiCssBaseline: {
      styleOverrides: {
        body: {
          backgroundImage: 'linear-gradient(to right, #1f4037, #99f2c8)' /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */,
          backgroundRepeat: 'no-repeat'
        },
      },
    },
  },
  typography: {
    fontFamily: [
      '-apple-system',
      'BlinkMacSystemFont',
      '"Segoe UI"',
      'Roboto',
      '"Helvetica Neue"',
      'Arial',
      'sans-serif',
      '"Apple Color Emoji"',
      '"Segoe UI Emoji"',
      '"Segoe UI Symbol"',
    ].join(','),
  },
});

darkTheme = responsiveFontSizes(darkTheme);

Amplify.configure(awsExports);

root.render(
  <React.StrictMode>
    <Authenticator.Provider>
      <BrowserRouter>
        <ThemeProvider theme={darkTheme}>
        <CssBaseline />
          <Banner />
          <Container maxWidth='md' style={{height: "100vh"}}>
              <Routes>
                <Route path="/" element={<App />} />
                <Route path="/login" element={<Login/>} />
                <Route path="/test" element ={<Test/>} />
                <Route path="/logout" element ={<RequireAuth><SignOut/></RequireAuth>} />
              </Routes>
          </Container>
        </ThemeProvider>
      </BrowserRouter>
    </Authenticator.Provider>
  </React.StrictMode>
);

reportWebVitals();

RequireAuth:

import { useLocation, Navigate } from 'react-router-dom';
import { useAuthenticator } from '@aws-amplify/ui-react';

export function RequireAuth({ children }) {
  const location = useLocation();
  const { route } = useAuthenticator((context) => [context.route]);
  if (route !== 'authenticated') {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }
  return children;
}
Mark
  • 1
  • 1
  • Please edit your post to include a [mcve] as we can't help diagnose or debug code we can't see. If you are just trying to implement route protection and authentication does this help answer your question? https://stackoverflow.com/a/66289280/8690857 – Drew Reese Jul 13 '22 at 04:58
  • Does this answer your question? [useLocation doesn't recognize state](https://stackoverflow.com/questions/61828145/uselocation-doesnt-recognize-state) – aswzen Jul 13 '22 at 05:00
  • 1
    @aswzen It's not *quite* the same thing. The link you provide is in reference to the older RRDv5 route props, which OFC don't exist in RRDv6. OP here is using the `useLocation` hook. – Drew Reese Jul 13 '22 at 05:00
  • @DrewReese I've added sample code. Thank you for the replies. – Mark Jul 13 '22 at 05:03
  • your state is undefined in location.state?.from?.pathname || '/'; try location?.state?.from?.pathname – Akhil Jul 13 '22 at 05:05
  • Can you share more complete code? Is there a router wrapping all this code? Can we see the `RequireAuth` wrapper component? – Drew Reese Jul 13 '22 at 05:05
  • @DrewReese I've added my index, requireauth and login function. – Mark Jul 13 '22 at 05:13
  • @Akhil Indeed, state is undefined because it doesn't seem to be existing under Location – Mark Jul 13 '22 at 05:13
  • I don't see any overt issues with the code you've shared. Would it be possible for you to create a *running* [codesandbox](https://codesandbox.io/) demo that reproduces the issue that we could inspect and debug live? – Drew Reese Jul 13 '22 at 05:22
  • @DrewReese Based on your answer here I managed to resolve the issue: https://stackoverflow.com/a/66289280/8690857 There were in fact some things happening: 1. Cloud9 still gives me the error on the line 2. If RequireAuth redirected, I did get the state 3. In my other routes I did not pass the state. So all my routes now pass the state like you showed in your example so now it is working. Cloud9 continues to give the error but I don't know why. Thank you though!! – Mark Jul 13 '22 at 05:28

0 Answers0