When I load the home page of my react-redux application I got the error
Encountered error "TypeError: Cannot read property 'search' of undefined" when prerendering App with {"location":"/","currency":"USD"}
I am getting error in following code
const UrlParser = {
getQueryVariable: (variable) => {
let query = window.location.search.substring(1);
let vars = query.split('&');
for (let i = 0; i < vars.length; i++) {
let pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) === variable) {
return decodeURIComponent(pair[1]);
}
}
}
}
export default UrlParser;
can anyone please help me
Edit
window.location on console gives
Location {href: "http://localhost:5000/", ancestorOrigins: DOMStringList, origin: "http://localhost:5000", replace: function,
assign: function…} ancestorOrigins:DOMStringListassign:function ()hash :"" host : "localhost:5000" hostname : "localhost" href : "http://localhost:5000/" origin : "http://localhost:5000" pathname : "/" port : "5000" protocol : "http:" reload : function reload() replace : function () search : "" toString : function toString() valueOf : function valueOf() Symbol(Symbol.toPrimitive) : undefined proto : Location
After much discussion, It's really hard to tell why assigning window.location.search.substring(1)
throws an error. One way to circumvent this issue is by using a try catch clause:
getQueryVariable: (variable) => {
let query;
try {
query = window.location.search.substring(1);
} catch(e) {
// window.location.search.substring(1) throws an error, set query
// to fallback value ''
console.log(e);
query = '';
}
let vars = query.split('&');
for (let i = 0; i < vars.length; i++) {
let pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) === variable) {
return decodeURIComponent(pair[1]);
}
}
}