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

JS string / Subsrting method undefine

I am building login and registration form in NextJS and MongoDB. Users can sign up and then login. I created a profile page. On profile page I want to display user information: name, email, created date.

If I am using substring() method I am getting:

TypeError: Cannot read properties of undefined (reading 'substring')

I was trying slice() method and the same typeError: as above. Can you tell me why and how to fix it? Thank you.

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

const [born, setBorn] = useState(user?.user?.createdAt)
console.log(born) // 2023-05-20T04:12:43.952Z

I would like to get 2023-05-20

This is my solution:

const created = born.substring(0,10)
console.log(created) // 2023-05-20 here is all good BUT!

If I put created to the body. I am getting error as I mentioned above.

<p>Created: {created}</p> // TypeError: Cannot read...

>Solution :

You may try the following.
The error you are encountering occurs because the born variable is undefined when you try to access it with the substring() method. It seems that the born state is not being set properly.

To fix this issue, you can ensure that the born state is set correctly before trying to use it. You can update your code as follows:

const [born, setBorn] = useState(user?.user?.createdAt || ''); // Set initial value as empty string if `createdAt` is undefined
console.log(born); // 2023-05-20T04:12:43.952Z

const created = born.substring(0, 10);
console.log(created); // 2023-05-20

<p>Created: {created}</p>

By providing a fallback value of an empty string ('') when createdAt is undefined, you avoid the error when accessing the substring() method.

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