One of the most common errors we record, “Cannot read properties of undefined (reading ‘length’)”, turned up in our own logs recently while looking into an issue with Microsoft Edge and the Facebook sdk. Let’s dive into this error, what it means, and how to fix it.
Breaking down the Message
TypeError: Cannot read properties of undefined (reading 'length')
In older browsers, this might also be shown as:
Cannot read property 'length' of undefined
TypeError is a subset of JavaScript Error that is thrown when code attempts to do something that does not exist on the target object.
This message indicates that our code expects to have an object with a length
property, but that object was not present. length
is commonly used on string
and array
, but a custom object could also have this property.
This is a blocking error, and script execution will stop when this error occurs.
Understanding the Root Cause
This error can be thrown for a lot of reasons, as it is incredibly common to reference the length
property of string
or array
during everyday development. For example, if we had a function that acts on a string argument, but is called without a string, we would see this error.
function foo(myString) { if (myString.length >= 10) { // do something } } foo(); // Whoops! TypeError
In our case, we were intercepting a call to fetch
, and we had assumed the url
property would be a string.
But, dear developer, it was not always a string. 🤦♂️.
We had some code like this that intercepted fetch requests and recorded some metadata if the request was correct. It looked something like this:
ourInterceptedFetch(options) { if (options.url.length <= 0) { // fail out } }
We were doing appropriate defensive type checking to make sure that the options
argument had a valid url
property. Unfortunately, fetch also accepts options
to be any object with a stringifier: an object with a toString
method. Like this:
fetch({ toString: function() { return `https://whatever.com/`; } });
In this case, options.url
is undefined, so when we try to check options.url.length
, it blows up with our error, “Cannot read property ‘length’ of undefined”. Ugh.
While this may be valid, it is a bit weird, right? We thought so too.
How to Fix It
So how do we fix this and prevent it from happening again?
1. Understand why your object is undefined
First and foremost, you need to understand why this happened before you can fix it. You are probably not doing exactly the same thing we are, so the reason your object is undefined may be somewhat different. Consider:
- Are you relying on a network response to be a certain shape?
- Are you processing user-input?
- Is an external function or library calling into your code?
Or maybe its just a logical bug somewhere in your code.
2. Add Defensive Checking
Anytime you don’t completely control the input into your code, you need to be defensively checking that arguments have the correct shape. API response change, functions get updated, and users do terrible, terrible things.
For instance, if you have a fetch
request that receives a JSON response with a foo
string property, you might have a defensive check that looks like this:
fetch("https://example.com/api") .then(resp => { return resp.json(); }) .then(json => { if (!json || typeof json.foo != 'string') { // Record an error, the payload is not the expected shape. } });
3. Monitor Your Environment
You’ll need to make sure that the issue is really fixed and that the problem stops happening. Mistakes happen, APIs change, and users are unpredictable. Just because your application works today, doesn’t mean an error won’t be discovered tomorrow. Tracking when exceptional events happen to your users gives you the context to understand and fix bugs faster. Check out TrackJS Error Monitoring for the fastest and easiest way to get started.
I am trying to read the json document from php and convert it needed in js, but an error occurs. :
cannot read properties of undefined (reading ‘length’)
What went wrong? How can I loop the result below without using length ?
Here’s the code:
What I have tried:
/*php */ $conn = db_connect(); $id = mysqli_fix_string( $conn, $id ); $Json_file = file_get_contents("files/sub/".$id."/".sub.json); print( $json_file ); /*.js */ $.ajax({ url: "./sub/view_sub.php", type:"GET", data: { id: id }, success: function( json ) { const result = JSON.parse( json ); console.log(result.sub) console.log(result.sub[1]); // OK result is 'serg' console.log(result.sub[2]); // OK result is 'dgf if( result.sub.length > 0 ){ <<== error let i = 0; for( const item of result.sub ){ foo_arr[id].input_text(i++, item ); } } } }); // console result >{1: 'serg', 2: 'dgf', 4: 'dfg ', 6: 'dfge ergre'} <== console.log(result.sub) uncaught typeError: Cannot read properties of undefined (reading 'length')
Solution 2
Quote:
This is my result /
console.log(result.sub) {1: 'serg', 2: 'dgf', 4: 'dfg ', 6: 'dfge ergre'}
Your result is not an array; it’s an object which happens to have numeric property names.
If you want to iterate over the properties of the object, you can use the Object.keys
method[^]:
const subKeys = Object.keys(result.sub); for (let i = 0; i < subKeys.length; i++) { foo_arr[id].input_text(i, result.sub[subKeys[i]]); }
Comments
Solution 1
Try using:
if( result.length > 0 )
Example:
const fruits = ["Banana", "Orange", "Apple", "Mango"]; let length = fruits.length;
result returns:
4
Comments
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
Top Experts | |
Last 24hrs | This month |
CodeProject,
20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8
+1 (416) 849-8900
Comments
Environment
- Operating System:
Linux
- Node Version:
v16.10.0
- Nuxt Version:
3.0.0-27265876.3cd4494
- Package Manager:
yarn@1.22.17
- Bundler:
Vite
- User Config:
serverMiddleware
- Runtime Modules:
-
- Build Modules:
-
Describe the bug
serverMiddleware
doesn’t work with express.js (4.17.1)
and throws «Cannot read properties of undefined (reading 'content-type')
» error
Reproduction
Clone a repository with the bug and run it as dev server
$ git clone https://github.com/martiliones/nuxt-express-bug $ cd nuxt-express-bug && yarn install $ yarn dev
Open http://localhost:3000/projects/
in your browser
Additional context
I tested serverMiddleware
with h3 and it works just fine:
// api/index.js import { createApp } from 'h3' const app = createApp() app.use('/projects', () => JSON.stringify([ { name: 'asdsad', type: ['asdsad', 'asdsad'] } ]))
Logs
Cannot read properties of undefined (reading 'content-type') at ServerResponse.getHeader (node:_http_outgoing:597:24) at ServerResponse.res.get (./node_modules/express/lib/response.js:789:15) at ServerResponse.json (./node_modules/express/lib/response.js:263:13) at file://./.nuxt/nitro/index.mjs:139:7 at Layer.handle [as handle_request] (./node_modules/express/lib/router/layer.js:95:5) at next (./node_modules/express/lib/router/route.js:137:13) at Route.dispatch (./node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (./node_modules/express/lib/router/layer.js:95:5) at ./node_modules/express/lib/router/index.js:281:22 at Function.process_params (./node_modules/express/lib/router/index.js:335:12)
The problem only seems to exist when the API is used while SSR. Requesting with postman does not throw any errors.
Any news on this ?
Endpoints work just fine for me, but it fails when called using useFetch
If you want to debug it, the issue is that express
sets the prototype of req
/res
to be the native Node classes, rather than the unenv
-provided classes we’re using in Nuxt. That means the internal object that Node uses to store headers is undefined and can’t be read from.
Ive also facing same issue, any workaround worth trying here?
Using the direct full URL eg
http://localhost:3000/api/whatever
Instead of
api/whatever
Worked for me ….
Thanks for the quick reply! it is indeed working to me as well
So is this a bug then? Using the full url works for me but would love to have the url relative
I’m not sure what are the full implications of using only the express Router instead of using the full express app. That being said i did find that doing the following will make the content-type error go away:
// Using the full express app this way will give the error: import express from ‘express’ const app = express() // … // Using only the Express Router import { Router } from ‘express’ const app = Router() // …
I ran into other problems doing it this way, issues to do with sessions and cookies. So i’m not confident this is not creating new problems but it may help someone else find a better solution.
I ended up writing my own router based on h3 that can handle different request methods and route parameters. It’s probably not the best approach, but if anyone wants to use it here it is: router.ts
Using the direct full URL eg
http://localhost:3000/api/whatever
Instead of
api/whatever
Worked for me ….
Thank you. That worked (in my dev environment)
But that is going to get complicated in a hosting environment
We eventually ended up setting an env variable called API_BASE which points to the api internal url that is used as the base for our fetch, we have one for each environment, bit annoying but manageable, will be more difficult if we will have dynamic preview environments without static domains..
…
On 19 Jan 2022, at 5:21, Rabbi Moshe Plotkin ***@***.***> wrote:
Using the direct full URL eg
http://localhost:3000/api/whatever
Instead of
api/whatever
Worked for me ….
Thank you. That worked (in my dev environment)
But that is going to get complicated in a hosting environment
—
Reply to this email directly, view it on GitHub, or unsubscribe.
You are receiving this because you commented.
Using the direct full URL eg
http://localhost:3000/api/whatever
Instead of
api/whatever
Worked for me ….Thank you. That worked (in my dev environment) But that is going to get complicated in a hosting environment
Yeah it is obviosly not ideal, I dont know why this solves it, it was just trial and error that i stumbled on it — I was originally convinced that I was just pulling the wrong endpoint, or had an extra /
or something — so I tried it on a whim
Using the full URL prevents Nitro from making a local call. So it’s a workaround with a performance cost.
I am also having this issue in RC4. Any proper fixes known?
The «fix» for this is using h3 instead of express. Since my last comment, h3 now supports HTTP methods and path parameters (in other words DON’T use the one I shared in a previous comment. It is a 100% worse than their implementation and is not maintained).
The proper fix will most likely be on express’ side since they are the ones overriding the objects with the wrong prototype.
The «fix» for this is using h3 instead of express. Since my last comment, h3 now supports HTTP methods and path parameters (in other words DON’T use the one I shared in a previous comment. It is a 100% worse than their implementation and is not maintained).
The proper fix will most likely be on express’ side since they are the ones overriding the objects with the wrong prototype.
could you create an issue on express? I don’t have enough understanding of the way this local communication works to provide a good issue description.
can someone explain to me how these local requests work?
So according to this comment, something like this should work:
import { IncomingMessage } from 'unenv/runtime/node/http/_request'
import { ServerResponse } from 'unenv/runtime/node/http/_response'
const app = express()
Object.setPrototypeOf(Object.getPrototypeOf(app.request), IncomingMessage.prototype)
Object.setPrototypeOf(Object.getPrototypeOf(app.response), ServerResponse.prototype)
… but it does not seem to do much (for me, anyways)
I’m also having this problem — mainly because I need to reuse complex middleware that is somewhat Express-coupled. I think there are two problems: (1) that Express overrides the req/res prototypes; (2) APIs exposed via an Express-embedded-in-h3/nitro/nuxtjs server need to be handled both via server-side-only and from external requests, and the req/res prototypes needed for these two scenarios are different.
It seems like there are 3 possible solutions:
(1) Change h3 to (have the option to) not use node.http’s res/req objects for incoming HTTP requests, so that overriding Express’s prototypes as indicated in the last comment might work across both kinds of API requests. (I would think this would be somewhat complicated.)
(2) Change the server-side-only fake res/req (unenv/runtime/fetch/call.mjs) to (have the option to) use the native node.http res/req objects instead. (Don’t know how accessible these objects are for direct instantiation though..)
(3) Change unjs’s polyfill-ish IncomingMessage/ServerResponse objects to more closely mirror nodejs’. (I would think this would become a maintenance nightmare over time if nodejs evolves their impls.)
Would any of the above be viable changes to nuxt/unjs?
If none of these can be implemented until Nuxt 3.0.0 releases I think an option for disabling local calls would make sense. This would still allow using relative routes but with a performance penalty. It could just use the loopback interface on the server and the public url on the client then.
@niwla23
If you don’t mind me asking: how would this look like in an express app? I’m not entirely understanding
@luischinchillagarcia When you request /test from SSR it seems to make a local request that is not going through the loopback interface but somehow stays in the process, at least that is how I understand it. But this feature only seems to work with h3, so it would be nice to have an option to have nuxt SSR make these requests over the loopback interface.
So on the Server Side /test
would simply be a request to http://localhost:3000/test
and on the client side it would still be /test
, but handled by the browser resulting in https://yourpublichhost.com/test.
Hopes this makes sense, but maybe I don’t understand correctly how local calls to h3 work.
I’ve set «SSR: false», so would not expect a local call to be made.
I get this error when running «nuxi build».
I’m not getting this error with «nuxi dev».
This piece of code fixes half of the problem:
import { IncomingMessage } from 'unenv/runtime/node/http/_request' import { ServerResponse } from 'unenv/runtime/node/http/_response' const app = express() Object.setPrototypeOf(Object.getPrototypeOf(app.request), IncomingMessage.prototype) Object.setPrototypeOf(Object.getPrototypeOf(app.response), ServerResponse.prototype)
After this fix, The error changes from «Cannot read …» to «Cannot set properties of undefined (setting ‘content-type’)»
martiliones
changed the title
Cannot read properties of undefined (reading ‘content-type’) in express js
Cannot read properties of undefined (reading ‘content-type’) using express js
Aug 24, 2022
I removed express.urlencoded({extended: true}) and it works.
danielroe
transferred this issue from nuxt/framework
Jan 19, 2023
Copy link
Sponsor
Collaborator
Can be closed as upstream is closed
“Cannot read properties of undefined in JavaScript” means JavaScript cannot read the properties of an object that you have not defined before. Let’s follow the article below to figure out how to solve this problem.
Common causes of the error “cannot read properties of undefined” in JavaScript
There are many causes of this problem, but the main cause is that JS can’t read the property of the object that stores the undefined value or the object is uninitialized.
Some cases cause this error:
- You are accessing an object that has an undefined data type or has not been assigned a value.
Example:
let nothing = undefined;
console.log(nothing.name);
Output:
Error: Cannot read properties of undefined (reading 'name')
- You are trying to call a method in the undefined object.
Example:
let nothing;
console.log(nothing.toString());
Output:
Error: Cannot read properties of undefined (reading 'toString')
Solutions for this error
Solution 1: Make sure the variable is not an undefined object before using it
Using the if
statement, you can easily check whether the variable is undefined.
let h1 = 'LearnshareIT';
if (h1) {
console.log('h1 is not an undefined object');
}
Output:
h1 is not an undefined object
Write code in the block scope of the if
statement to avoid the error.
Solution 2: Set the default value before reading the properties
You can set the default value for any variables with the nullish coalescing operator ??
as long as the default value cannot be null
or undefined
.
const defaultObj = {
heading: 'LearnshareIT',
};
let h1 = undefined;
let heading = h1 ?? defaultObj.heading;
console.log(heading);
Output:
LearnshareIT
Now, you can read any properties of the heading
object and never get the “cannot read properties of undefined in JavaScript” error.
Solution 3: Using optional chaining (?.
)
Optional chaining accesses the property or method of an object. If the object is undefined or the property does not exist, it returns undefined instead of throwing an error. Therefore, using optional chaining can help us avoid the error.
let h1 = {
content: 'LearnshareIT',
style: {
color: 'grey',
font: 'Lato',
},
};
let h2;
console.log(h1?.style?.color);
console.log(h2?.content);
Output:
grey
undefined
Summary
The “cannot read properties of undefined” error in JavaScript is very common when building web applications. However, by understanding the nature of the problem, we can avoid them easily. Thanks for reading, and I hope this post helps you avoid mistakes.
Hi, I’m Cora Lopez. I have a passion for teaching programming languages such as Python, Java, Php, Javascript … I’m creating the free python course online. I hope this helps you in your learning journey.
Name of the university: HCMUE
Major: IT
Programming Languages: HTML/CSS/Javascript, PHP/sql/laravel, Python, Java
The TypeError: Cannot read property of undefined
is one of the most common type errors in JavaScript. It occurs when a property is read or a function is called on an undefined variable.
Install the JavaScript SDK to identify and fix these undefined errors
Error message:
TypeError: Cannot read properties of undefined (reading x)
Error type:
TypeError
What Causes TypeError: Cannot Read Property of Undefined
Undefined means that a variable has been declared but has not been assigned a value.
In JavaScript, properties and functions can only belong to objects. Since undefined
is not an object type, calling a function or a property on such a variable causes the TypeError: Cannot read property of undefined
.
TypeError: Cannot Read Property of Undefined Example
Here’s an example of a JavaScript TypeError: Cannot read property of undefined
thrown when a property is attempted to be read on an undefined variable:
function myFunc(a) {
console.log(a.b);
}
var myVar;
myFunc(myVar);
Since the variable myVar
is declared but not initialized, it is undefined. When it is passed to the myFunc
function, the property b
is attempted to be accessed. Since a
is undefined at that point, running the code causes the following error:
TypeError: Cannot read properties of undefined (reading 'b')
How to Avoid TypeError: Cannot Read Property of Undefined
When such an error is encountered, it should be ensured that the variable causing the error is assigned a value:
function myFunc(a) {
console.log(a.b);
}
var myVar = {
b: 'myProperty'
};
myFunc(myVar);
In the above example, the myVar
variable is initialized as an object with a property b
that is a string. The above code runs successfully and produces the following output on the browser console:
myProperty
To avoid coming across situations where undefined variables may be accessed accidentally, an if
check should be added before dealing with such variables:
if (myVar !== undefined) {
...
}
if (typeof(myVar) !== 'undefined') {
...
}
Updating the previous example to include an if
check:
function myFunc(a) {
if (a !== undefined) {
console.log(a.b);
}
}
var myVar;
myFunc(myVar);
Running the above code avoids the error since the property b
is only accessed if a
is not undefined
.
Here is how you can handle errors using a try { } catch (e) { }
block.
// Caught errors
try {
//Place your code inside this try, catch block
//Any error can now be caught and managed
} catch (e) {
Rollbar.error("Something went wrong", e);
console.log("Something went wrong", e);
}
Here is how you can setup a JavaScript Error handler: Setup JavaScript Error Handler
Where TypeError Resides in the JavaScript Exception Hierarchy
JavaScript provides a number of core objects that allow for simple exception and error management. Error handling is typically done through the generic Error
object or from a number of built-in core error objects, shown below:
- Error
- InternalError
- RangeError
- ReferenceError
- SyntaxError
- TypeError
- Cannot read property of undefined
As seen from the hierarchy above, TypeError
is a built-in JavaScript error object that allows for the administration of such errors. The “Cannot read property of undefined” TypeError
is a descendant of the TypeError
object.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing JavaScript errors easier than ever. Sign Up Today!
Question:
I have a Json File which contains blog, when I am passing
match: {
params: { date },
},
it is failing
it is redirecting to the page
http://localhost:3000/blog-details/1 but after that it is loosing all the states as the page is throwing unexpected error
My File is
import React from "react";
import PropTypes from "prop-types";
import NewsletterArea from "../containers/global/newsletter";
import PageBanner from "../containers/global/page-banner";
import Footer from "../layouts/footer";
import Header from "../layouts/header";
import Layout from "../layouts/index";
import BlogData from "../data/blog.json";
import BlogItemContainer from "../containers/blog/blog-item";
import { slugify } from "../utils";
import ScrollToTop from "../components/scroll-to-top";
import SEO from "../components/seo";
const BlogDate = ({
match: {
params: { date },
},
}) => {
const data = BlogData.filter((blog) => slugify(blog.date) === date);
const dateTitle = data[0].date;
return (
<React.Fragment>
<Layout>
<SEO title="Nise-Comport – Blog Date" />
<div className="wrapper">
<Header />
<PageBanner
title={dateTitle}
excerpt="Pleasure rationally encounter consequences <br />
are extremely painful great oppurtunity"
image="/images/blog/banner.png"
/>
<BlogItemContainer data={data} />
<NewsletterArea />
<Footer />
<ScrollToTop />
</div>
</Layout>
</React.Fragment>
);
};
BlogDate.propTypes = {
match: PropTypes.shape({
params: PropTypes.shape({
date: PropTypes.string,
}),
}),
};
export default BlogDate;
My json file is
[
{
"id": 1,
"media": {
"rcImage": "./images/blog/post/aadhaar-post.png",
"gridImage": "./images/blog/aadhaar.png",
"largeImage": "./images/blog-details/aadhaar-banner.png"
},
"title": "Aadhaar Demographic Update",
"author": "Shubham",
"date": "1 January, 2021",
"categories": ["Service"],
"tags": [
"Aadhaar",
"Demographic Update",
"CSC",
"Pragya Kendra",
"Digital Seva",
"Telco",
"India",
"NISE-COMPORT",
"NISE"
],
"body": [
"<p class='pb-2'>We have happy to share that we have started Aadhaar Demographic update service<br class='d-none d-xl-block' /> We currently provide the following mentioned service below </p>",
"<div class='blog-details-list'><p><i class='fa fa-angle-double-right'></i>Mobile Update / Correction</p><p><i class='fa fa-angle-double-right'></i>Email Id Update / Correction</p><p><i class='fa fa-angle-double-right'></i>Name Update / Correction</p><p><i class='fa fa-angle-double-right'></i>Address Update / Correction</p><p><i class='fa fa-angle-double-right'></i>DOB Update / Correction</p></div>",
"<div class='blog-qutation'><p>Aadhaar - AAM ADMI KA ADHIKAR </p><i class='icofont-quote-right'>UIDAI</i></div>",
"<div class='blog-details-grid'><div class='row mb-n7'><div class='col mb-7'><p>To avail this service , user / candidate need to take an prior appointment as per Covid guideline, and shall maintain safety regulation at the premises. Note: Kindly provide the Original document as well as prescribed documentation as per provide by UIDAI Guideline. </p></div><div class='col mb-7 text-end'><img class='d-block mx-auto mx-lg-0' src='/images/blog-details/2.png' alt='img' /></div></p></div></div></div>"
]
},
{
"id": 2,
"media": {
"rcImage": "./images/blog/post/2.png",
"gridImage": "images/blog/pan.png",
"largeImage": "./images/blog-details/pan-banner.png"
},
"title": "Pan Card Service",
"author": "Sanjay Kumar",
"date": "20 September, 2018",
"categories": ["Service"],
"tags": [
"CSC",
"Pragya Kendra",
"Digital Seva",
"Telco",
"India",
"NISE-COMPORT",
"NISE",
"PAN",
"NSDL",
"UTI"
],
"body": [
"<p class='pb-2'>We provide Pan service, where user can either apply for new / correction / lost. <br class='d-none d-xl-block' /> we work with major Pan authorised company which is tied up with CSC </p>",
"<div class='blog-details-list'><p><i class='fa fa-angle-double-right'></i>UTI</p><p><i class='fa fa-angle-double-right'></i>NSDL</p></div>",
"<div class='blog-qutation'><p>BUILDING A GOOD CUSTOMER EXPERIENCE DOES NOT HAPPEN BY ACCIDENT. IT HAPPENS BY DESIGN</p><i class='icofont-quote-right'>Anonymous</i></div>",
"<div class='blog-details-grid'><div class='row mb-n7'><div class='col mb-7'><p>For applying Pan card, user need to visit the center (If applying in Physical mode) and provide a copy of Aadhaar & two Passport size photos, for correction additional Pan card copy is required with the correcting details.<br> Do provide the correct details ,if there is any Incorrect data or document is provided. User/Applicant has to bear the charges. </p></div><div class='col mb-7 text-end'><img class='d-block mx-auto mx-lg-0' src='/images/blog-details/2.png' alt='img' /></div><div class='col-12 mb-7'><p class='pt-2>Pleasure rationally encounter consequences that are extremely painful. Nor again there who loves or pursues or desires to obtain voluptas sit aspernatur aut odit aut fugit, sed consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</p></div></div></div>"
]
}
]
Getting error in Console
blog-details.js:13 Uncaught TypeError: Cannot read properties of undefined (reading 'params')
at BlogDetailsPage (blog-details.js:13:1)
at renderWithHooks (react-dom.development.js:14985:1)
at mountIndeterminateComponent (react-dom.development.js:17811:1)
at beginWork (react-dom.development.js:19049:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at beginWork$1 (react-dom.development.js:23964:1)
at performUnitOfWork (react-dom.development.js:22776:1)
at workLoopSync (react-dom.development.js:22707:1)
also
react-dom.development.js:20085 The above error occurred in the <BlogDetailsPage> component:
at BlogDetailsPage (http://localhost:3000/static/js/bundle.js:14148:7)
at Routes (http://localhost:3000/static/js/bundle.js:60259:5)
at NavScrollTop (http://localhost:3000/static/js/bundle.js:3961:51)
at Wrapper (http://localhost:3000/static/js/bundle.js:4035:78)
at Router (http://localhost:3000/static/js/bundle.js:60192:15)
at BrowserRouter (http://localhost:3000/static/js/bundle.js:59668:5)
at App
Consider adding an error boundary to your tree to customize error handling behavior.
Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.
what should I do ?
Answer:
It appears you are using react-router-dom@6
so there are no longer any route props. In other words, props.match
is undefined. Reading into props.match.params
then throws the error.
Use the useParams
hook to access the date
route param.
import { useParams } from 'react-router-dom';
const BlogDate = () => {
const { date } = useParams();
const data = BlogData.filter((blog) => slugify(blog.date) === date);
const dateTitle = data[0].date;
return (
<React.Fragment>
<Layout>
<SEO title="Nise-Comport – Blog Date" />
<div className="wrapper">
<Header />
<PageBanner
title={dateTitle}
excerpt="Pleasure rationally encounter consequences <br />
are extremely painful great oppurtunity"
image="/images/blog/banner.png"
/>
<BlogItemContainer data={data} />
<NewsletterArea />
<Footer />
<ScrollToTop />
</div>
</Layout>
</React.Fragment>
);
};
export default BlogDate;
If you have better answer, please add a comment about this, thank you!