Posted By: Anonymous
To start things off, I don’t have any nuxt-link
s without the to
attribute.
Now, I have routes like this
- /blog/{category}
- /blog/tag/{tag}
- /blog/{category}/{post}
I have this in my nuxt.config.js
file:
generate: {
routes: function() {
return Promise.all([
axios.get('https://api.example.com/categories').then(res => {
return res.data.map(category => {
return {
route: '/blog/' + category.slug,
payload: category
}
})
}),
axios.get('https://api.example.com/tags').then(res => {
return res.data.map(tag => {
return {
route: '/blog/tag/' + tag.slug,
payload: tag
}
})
}),
axios.get('https://api.example.com/posts').then(res => {
return res.data.map(post => {
return {
route: `/blog/${post.category.slug}/${post.slug}`,
payload: post
}
})
})
])
}
},
When I run yarn generate
, it starts off good, then around the end it outputs the error from the title, but it doesn’t cancel the execution. This is the whole error:
ERROR undefined 20:47:14
TypeError: Cannot read property '_normalized' of undefined
at normalizeLocation (C:Users...Codemyprojectmysitenode_modulesvue-routerdistvue-router.common.js:1297:12)
at VueRouter.resolve (C:Users...Codemyprojectmysitenode_modulesvue-routerdistvue-router.common.js:2627:18)
at He (webpack/bootstrap:2:0)
at async t.default (webpack/bootstrap:2:0)
How do I properly generate my dynamic routes for static hosting? This seems quite troublesome.
Solution
I’ll admit I haven’t done this before, but based on the docs, it looks like you’d probably need to return a single array. Your promise will resolve to an array of arrays. Maybe something like this:
const buildRoutes = async () => {
const [r1, r2, r3] = await Promise.all([
axios.get('https://api.example.com/categories').then(res => {
return res.data.map(category => {
return {
route: `/blog/${category.slug}`,
payload: category,
};
});
}),
axios.get('https://api.example.com/tags').then(res => {
return res.data.map(tag => {
return {
route: `/blog/tag/${tag.slug}`,
payload: tag,
};
});
}),
axios.get('https://api.example.com/posts').then(res => {
return res.data.map(post => {
return {
route: `/blog/${post.category.slug}/${post.slug}`,
payload: post,
};
});
}),
]);
return [...r1, ...r2, ...r3];
};
And then:
generate: { routes: buildRoutes }
Answered By: Anonymous
Related Articles
- Problems Installing CRA & NextJS from NPM (Error:…
- Angular: Can’t find Promise, Map, Set and Iterator
- next js with redux and reselect
- «gatsby-source-airtable» threw an error while running the…
- Run nuxt on https locally – problem with nuxt.config.js
- Data flow in Polymer Topeka example
- Heroku deploy fails with react and next js
- NEXT.JS with persist redux showing unexpected behaviour
- Nested routes in Ember JS and Ember Rails
- Updating a model w/ Backbone.js + Rails not working (PUT…
Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.
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!
В консоли своего веб-сайта я вижу следующую ошибку:
vue.esm.js?a026:628 [Vue warn]: Error in render: "TypeError: Cannot read property 'id' of undefined"
found in
---> <ApiInstellingen> at src/views/settings/analytics.vue
<Anonymous>
<CWrapper>
<TheContainer> at src/containers/TheContainer.vue
<App> at src/App.vue
<Root>
Я видел много подобных проблем в Интернете и знаю, что это связано с тем, что я пытаюсь получить доступ к данным до того, как они будут обработаны. Ни одно из найденных мной решений не помогло.
Вот мой код:
<template>
<div>
<p> {{allAnalytics[0].id}} </p>
</div>
</template>
<script>
import { mapGetters, mapActions } from "vuex";
export default {
name: "apiInstellingen",
methods: {
...mapActions(['fetchAnalytics'])
},
created() {
this.fetchAnalytics();
},
computed: mapGetters(['allAnalytics']),
};
</script>
Кто-нибудь знает решение, которое сработает в моем случае? Я пробовал v-if, объявляя в состоянии, объявляя переменную в данных, но ничего из этого, похоже, не работает …
Спасибо!
2 ответа
Лучший ответ
Это связано с тем, что ваш массив allAnalytics
не определен на момент его использования (выборка еще не выполнена), поэтому вы не можете получить доступ к индексу 0.
Вы можете добавить такое условие рендеринга
<template>
<div>
<p v-if"allAnalytics && allAnalytics[0]"> {{allAnalytics[0].id}} </p>
</div>
0
Andy
26 Авг 2020 в 16:12
Что мы можем почерпнуть из сообщения об ошибке, так это то, что ваш массив allAnalytics
создается при рендеринге шаблона, но у него нет никакого содержимого.
Я думаю, если вы поместите v-if="allAnalytics.length > 0
в родительский div в шаблоне, вы не увидите этой ошибки. Но что еще более важно, вы должны спросить себя: «Должен ли этот массив allAnalytics
когда-либо иметь нулевую длину?»
Возможно, вам нужно добавить директиву v-for
к дочернему тегу <p>
для итерации массива allAnalytics
, как показано ниже. Конечно, это зависит от вашего варианта использования.
<template>
<div>
<p v-for="item in allAnalytics" :key="item.id" > {{item.id}} </p>
</div>
</template>
0
Tanner
26 Авг 2020 в 15:33