0

I seem to have a problem on my React Frontend I am working on my Reset.js page and I keep getting an error as

TypeError: Cannot read property 'params' of undefined

It happens as soon as I route to the Reset.js page and how this was working is that when a User forgets their password they are sent an email in order to Reset their password using jwt and when the link is clicked on the email it would route you to the Reset.js page and this is where you will fill in credentials to reset your password.

But in the process when the route is reached I get a TypeError: Cannot read property 'params' of undefined Error and this is the affected React js line of code shown below.

  14 | const { password1, password2, textChange, token } = formData;
  15 | 
  16 | useEffect(() => {
> 17 |     let token = match.params.token // **Error is caused here Cannot read property 'params' of undefined**
     | ^  18 |     if(token) {
  19 |         setFormData({...formData, token,})
  20 |     }

This is also a screenshot to the Chrome Error for easy viewing. screenshot

And here is the full code for my Reset.js page in React.

import React, { useState, useEffect } from 'react';
import authSvg from '../assets/reset.svg';
import { ToastContainer, toast } from 'react-toastify';
import axios from 'axios';

const Reset = ({match}) => {
  const [formData, setFormData] = useState({
      password1: '',
      password2: '',
      token: '',
    textChange: 'Submit'
  });
    // eslint-disable-next-line no-unused-vars
    const { password1, password2, textChange, token } = formData;
    
    useEffect(() => {
        let token = match.params.token // **Error is caused here Cannot read property 'params' of undefined**
        if(token) {
            setFormData({...formData, token,})
        }
        
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])
  const handleChange = text => e => {
    setFormData({ ...formData, [text]: e.target.value });
  };
    const handleSubmit = e => {
      console.log(password1, password2)
    e.preventDefault();
    if ((password1 === password2) && password1 && password2) {
      setFormData({ ...formData, textChange: 'Submitting' });
      axios
        .put(`${process.env.REACT_APP_API_URL}/password/reset`, {
            newPassword: password1,
            resetPasswordLink: token
        })
        .then(res => {
          console.log(res.data.message)
            setFormData({
              ...formData,
               password1: '',
              password2: ''
            });
            toast.success(res.data.message);
          
        })
        .catch(err => {
          toast.error('Something is wrong try again');
        });
    } else {
      toast.error('Passwords don\'t matches');
    }
  };
  return (
    <div className='min-h-screen bg-gray-100 text-gray-900 flex justify-center'>
      <ToastContainer />
      <div className='max-w-screen-xl m-0 sm:m-20 bg-white shadow sm:rounded-lg flex justify-center flex-1'>
        <div className='lg:w-1/2 xl:w-5/12 p-6 sm:p-12'>
          <div className='mt-12 flex flex-col items-center'>
            <h1 className='text-2xl xl:text-3xl font-extrabold'>
              Reset Your Password
            </h1>
            <div className='w-full flex-1 mt-8 text-indigo-500'>
              
              <form
                className='mx-auto max-w-xs relative '
                onSubmit={handleSubmit}
              >
                <input
                  className='w-full px-8 py-4 rounded-lg font-medium bg-gray-100 border border-gray-200 placeholder-gray-500 text-sm focus:outline-none focus:border-gray-400 focus:bg-white'
                  type='password'
                  placeholder='password'
                  onChange={handleChange('password1')}
                  value={password1}
                  />
                  <input
                  className='w-full mt-5 px-8 py-4 rounded-lg font-medium bg-gray-100 border border-gray-200 placeholder-gray-500 text-sm focus:outline-none focus:border-gray-400 focus:bg-white'
                  type='password'
                  placeholder='Confirm password'
                  onChange={handleChange('password2')}
                  value={password2}
                />
                <button
                  type='submit'
                  className='mt-5 tracking-wide font-semibold bg-indigo-500 text-gray-100 w-full py-4 rounded-lg hover:bg-indigo-700 transition-all duration-300 ease-in-out flex items-center justify-center focus:shadow-outline focus:outline-none'
                >
                  <i className='fas fa-sign-in-alt  w-6  -ml-2' />
                  <span className='ml-3'>Submit</span>
                </button>
              </form>
            </div>
          </div>
        </div>
        <div className='flex-1 bg-indigo-100 text-center hidden lg:flex'>
          <div
            className='m-12 xl:m-16 w-full bg-contain bg-center bg-no-repeat'
            style={{ backgroundImage: `url(${authSvg})` }}
          ></div>
        </div>
      </div>
      ;
    </div>
  );
};

export default Reset;

I also tried to fix it by adding useParams though it didn't seem to workout as planned but this is the fix I tried making and didn't workout so I decided to reach out for some help,

This is what I had tried out below;

import { useParams } from 'react-router-dom';
import jwt from 'jsonwebtoken'; //added this because of the way I was using jwt.decode

    textChange: 'Submit'
  });
    // eslint-disable-next-line no-unused-vars
    const { password1, password2, textChange } = formData; //I removed token from here since we were calling it on line 21 in the params below
    // const { password1, password2, textChange, token } = formData; //this is the original code format and the one above is what I edited.
    
    const { token } = useParams();
    
    useEffect(() => {
        let password = jwt.decode(token); //added jwt.decode(token) here though at first it was match.params.token
        // let token = match.params.token
        if(token) {
            setFormData({...formData,password, token,}) //added password here tho it wasnt supposed to be their as reference to the original code.
        }
        
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

The Error Displayed when I tried out the above code with useParams read as in the Chrome console.

PUT http://localhost:4000/api/password/reset 400 (Bad Request)

Below is the Error but in a Screenshot form for easy viewing but its the same as the one above. 400 screenshot And then below are the routes i was using for my Reset.js Page

import { Navigate } from 'react-router-dom';
import DashboardLayout from 'src/components/DashboardLayout';
import MainLayout from 'src/components/MainLayout';
import Account from 'src/pages/Account';
import CustomerList from 'src/pages/CustomerList';
import AssistantList from 'src/pages/AssistantList';
import MarketList from 'src/pages/MarketList';
import Dashboard from 'src/pages/Dashboard';
import Login from 'src/pages/Login';
import NotFound from 'src/pages/NotFound';
import ProductList from 'src/pages/ProductList';
import Register from 'src/pages/Register';
import Settings from 'src/pages/Settings';
import Activate from 'src/pages/Activate';
import Forget from 'src/pages/Forget';
import Reset from 'src/pages/Reset'; //This is how I imported my Reset.js Page

const routes = [
  {
    path: 'app',
    element: <DashboardLayout />,
    children: [
      { path: 'account', element: <Account /> },
      { path: 'assistants', element: <AssistantList /> },
      { path: 'customers', element: <CustomerList /> },
      { path: 'dashboard', element: <Dashboard /> },
      { path: 'markets', element: <MarketList /> },
      { path: 'products', element: <ProductList /> },
      { path: 'settings', element: <Settings /> },
      { path: '*', element: <Navigate to="/404" /> }
    ]
  },
  {
    path: '/',
    element: <MainLayout />,
    children: [
      { path: 'login', element: <Login /> },
      { path: 'register', element: <Register /> },
      { path: '404', element: <NotFound /> },
      { path: '/', element: <Navigate to="/app/dashboard" /> },
      { path: '*', element: <Navigate to="/404" /> },
      { path: '/users/activate/:token', element: <Activate /> },
      { path: '/users/password/forget', element: <Forget /> },
      { path: '/users/password/reset/:token', element: <Reset /> } //Here is how I routed my reset.js page
    ]
  }
];

export default routes;
9
  • 1
    can you add the routes file as well? Jun 14, 2021 at 4:31
  • @AmilaSenadheera I have successfully added the Routes
    – AJ PHIL
    Jun 14, 2021 at 5:25
  • @AJPHIL which error did you get using useParams?
    – KOseare
    Jun 14, 2021 at 17:44
  • @KOseare For now I have been trying to figure out if if it was network issue but it doesn't seem so this is a screenshot image to the error I got imgur.com/lC1u59B reading as "Failed to load resource: the server responded with a status of 400 (Bad Request)" and here is the link to screenshot image imgur.com/iAMUwv4 to the code I updated
    – AJ PHIL
    Jun 15, 2021 at 9:49
  • @KOseare Ignore the first error this is the error am getting now PUT localhost:4000/api/password/reset 400 (Bad Request) I think the first one error was because of a network issue but now this is the correct error am getting I have also updated the Question above and you could be able to use it for reference too, also I have not changed the code its the same as the way I sent it in the recent comment above.
    – AJ PHIL
    Jun 15, 2021 at 10:38

1 Answer 1

0

Wrap your Reset component with withRouter (https://reactrouter.com/web/api/withRouter)

10
  • I added this line ( import { withRouter } from "react-router"; and then edited my export component to "export default withRouter(Reset)" but I got an error that says "Attempted import error: 'withRouter' is not exported from 'react-router'. in the Chrome Browser
    – AJ PHIL
    Jun 14, 2021 at 5:41
  • It should be imported from react-router-dom
    – Anil Kumar
    Jun 14, 2021 at 5:52
  • I added that too and it didn't work could the issue be because am using react router v6 beta
    – AJ PHIL
    Jun 14, 2021 at 5:57
  • Here is a screenshot just to verify imgur.com/undefined
    – AJ PHIL
    Jun 14, 2021 at 6:14
  • @AJPHIL I cant see the screenshot though
    – Anil Kumar
    Jun 14, 2021 at 6:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.