How to keep props data persisted in Vue?

Viewed 656

I have an application that is simplified into 4 Vue components:

  1. TextbookSelection
  2. TextbookView
  3. ChapterView
  4. Textbook Header

In my TextbookSelection component, I make an API call to retrieve all my available textbooks from my database. I then populate the front end with the data and dynamically create router links that will take the user to the next vue component, TextbookView if they click on one of them. I pass in a textbook data object as a prop that contains info about this textbook so that the TextbookView component can use it to populate instead of calling for the textbook data again.

In my TextbookSelection.vue, these router-links are created.

<router-link
    :to="{
      name: 'TextbookView',
      params: { textbook: textbook},
    }"

In my TextbookView, I have props: ["textbook"] written. I also have a TextbookHeader component in there that displays all the info about the selected textbook, so I pass in the textbook data in as a prop to the TextbookHeadercomponent as well. I have this as a separate vue component because I want the header to persist as the user goes further into the textbook, such as the ChapterView component. So as you can see, I am taking the same textbook data object I received from my first component (TextbookSelection) and passing it into every component if the user goes deeper into the textbook.

This works on the first pass; the user can select a textbook and it displays all the correct textbook information in the header. But then problem arises when the user hits "back" in their browser, or if they refresh the page. Suddenly, the header disappears because the prop data (Textbook data object) is now missing.

Error in render: "TypeError: Cannot read property 'id' of undefined"

found in

---> <TextbookHeaderView> at src/components/TextbookHeader.vue
       <ChapterView> at src/components/ChapterView.vue
         <App> at src/App.vue

How should I approach this problem? I don't know if what I'm doing is the correct way or not, but basically what I'd like is:

  1. Have a header vue component
  2. Have textbook data be persisted (user can go back and forth/refresh and the header will still have correct info)
  3. Not have to constantly pull in data whenever the header component is created
1 Answers

I would recommend you use VueX for state management. You could have an action that fetches your data from the database upon the creation of your home component and then update the store according to the fetched data. This allows all your components to have access to your data that is persisted through routing. Your TextbookHeader and all other components then have a single source of truth (the Store) and you don't have to re-fetch data (which you shouldn't anyway). For more information on Vuex, please visit the official documentation

Related