JK31
JK31

Reputation: 55

Vue component throws errors before rendered?

The Home view contains two components. Filter and Results. The component Results depends heavily on the results of vuex store data that is affected by the Filter component. After the filters are applied and the user clicks on a button in Filter the needed data for Results is created in the store and this component should be then rendered below Filter.

Here is the problem. When I open the Home view, the Results component throws errors in the console like "TypeError: Cannot read property '0' of undefined". This is expected as the data does not exist yet. I tried to render Results conditionally with <Results v-if="$store.state.data != {}" />. This prevents the rendering when the user enters the page and renders Results once the data is loaded after the button is clicked, but nevertheless Results throws the same errors as before when the page is opened.

One potential solution I have is that I can enter dummy data in the store to prevent errors (and then render with other condition). But there must be a way that works without dummy data.

Upvotes: 0

Views: 389

Answers (1)

Jordan
Jordan

Reputation: 2371

You've already identified the solution yourself: Using default dummy data on the object itself.

This would be the standard and optimal approach.

If you do this, you need to realise that Vuex doesn't work well with nested, relation data.

Typically, you'd want to normalise your data so that's flat and mapped via relationships.

You can learn more about the need to normalise state here

https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape/

It's about Redux, but the concepts are relevant to Vuex too.

To do this, you'd use Vue ORM to normalise the complex data. After normalisation, the objects in the Vuex will be much easier to manage, update and query.

Doing this also prevents Vuex from throwing errors when you attempt to access/update data from a nested object where the data doesn't currently exist (think nested data where it's comments and replies to comments).

This also has the added benefits of making your data easier to work with and understand programatically.

Upvotes: 1

Related Questions