1

I am trying to create private routes using react-private-route to lead a user to an authorized /panel page if the authentication is successful:

https://github.com/hansfpc/react-private-route

For authentication, the submit button sends a mutation request to the graphql backend. If the authentication is succesful, the backend then sends back a token, which is stored in localStorage. Here's what my code for my login page looks like: Do I need to make amends here?

const LoginMutation = gql`
mutation LoginMutation($email: String!, $password: String!) {
  loginEmail(email: $email, password: $password)
}
`;

const schema = Yup.object({
  email: Yup
    .string()
    .email('Invalid Email')
    .required('Please Enter your Email'),
  password: Yup
    .string()
    .required('Please Enter your password')
});

function LoginPage (){
  const [state, setState] = useState({
    email: '',
    password: '',
    loggedIn: false,
  });  


  function submitForm(LoginMutation: any) {
    const { email, password } = state;
    console.log(email, password)
    if(email && password){
      LoginMutation({
        variables: {
            email: email,
            password: password,
        },
    }).then(({ data }: any) => {
      localStorage.setItem('token', data.loginEmail);
    })
    .catch(console.log)

    }
  }

    return (
      <Mutation mutation={LoginMutation}>
        {(LoginMutation: any) => (
              <Typography component="h1" variant="h5">
                Sign in
              </Typography>
              <Formik
                initialValues={{ email: '', password: '' }}
                onSubmit={(values, actions) => {
                  setTimeout(() => {
                    alert(JSON.stringify(values, null, 2));
                    actions.setSubmitting(false);
                  }, 1000);
                }}
                validationSchema={schema}
              >
                {props => {
                  const {
                    values: { email, password },
                    errors,
                    touched,
                    handleChange,
                    isValid,
                    setFieldTouched
                  } = props;
                  const change = (name: string, e: any) => {
                    e.persist();                
                    handleChange(e);
                    setFieldTouched(name, true, false);
                    setState( prevState  => ({ ...prevState,   [name]: e.target.value }));  
                  };
                  return (
                    <form style={{ width: '100%' }} onSubmit={e => {e.preventDefault();submitForm(LoginMutation)}}>
                      <TextField
                        variant="outlined"
                        margin="normal"
                        id="email"
                        fullWidth
                        name="email"
                        helperText={touched.email ? errors.email : ""}
                        error={touched.email && Boolean(errors.email)}
                        label="Email"     
                        value={email}
                        onChange={change.bind(null, "email")}
                      />
                      <TextField
                        variant="outlined"
                        margin="normal"
                        fullWidth
                        id="password"
                        name="password"
                        helperText={touched.password ? errors.password : ""}
                        error={touched.password && Boolean(errors.password)}
                        label="Password"
                        type="password"
                        value={password}
                        onChange={change.bind(null, "password")}
                      />
                      <FormControlLabel
                        control={<Checkbox value="remember" color="primary" />}
                        label="Remember me"
                      />
                      <br />
                      <Button className='button-center'
                        type="submit"
                        disabled={!isValid || !email || !password}
                      >
                        Submit</Button>
                    </form>
                  )
                }}
              </Formik>
            </div>
          )
        }
      </Mutation>
    );
}

export default LoginPage;

Now I don't quite understand how I should modify this code in a way that I can set my private route if the token is being returned.

Some conditional statements perhaps but how and where? The example on the GitHub repo of react-private-route has isAuthenticated={!!isLoggedIn() /* this method returns true or false */}property. How can I create this function according to my code?

Here are few example solutions for Typescript but I don't understand how to use them with local storage How to rewrite the protected/private route using TypeScript and React-Router 4 and 5?

x89
  • 2,798
  • 5
  • 46
  • 110

1 Answers1

1

You can use like this if you have token stored in localstorage.

import { Redirect } from "react-router";
const PrivateRoute = ({ component: Component, ...props }) => {
  return (
    <Route
      {...props}
      render={innerProps =>
        localStorage.getItem("Token") ? (
          <Component {...innerProps} />
        ) : (
          <Redirect
            to={{
              pathname: "/",
              state: { from: props.location }
            }}
          />
        )
      }
    />
  );
ROHIT RAJ
  • 198
  • 2
  • 9
  • If I copy this into my App.tsx file, I get an error on Component saying that: ```Binding element 'Component' implicitly has an 'any' type.```This is typescript – x89 Feb 25 '20 at 15:07