简体   繁体   中英

storing firebase data in localstorage then pushing to vue data()

I'm not sure if I'm on the right track, but I'm trying to store some firebase data into my localstorage on my created() hook and then push it to my vue data() so I can render it in my app. But my localstorage isn't setting the data from firebase properly, so when I reference it in render my articles property is blank:(

I have some sample articles in my articles[] to show the structure of my data coming from firebase *the data does render properly as is when not referenced from localstorage

maybe someone can point me in the right direction, I think the issue has to be with my call to set data to localstorage

here is my component

<template> </template>

<script>
const fb = require('../../fireconfig.js')

export default {
  name: 'Home',
  data:function() {
    return{
       articles: [
         {
           title: 'modern web app security',
           body: 'some content here about web app security',
           image: 'dd',
           tags: ['cyber security','web apps', 'web development']
        },
         {
           title: 'intro to ArcGIS',
           body: 'an article to show users how to do GIS stuff',
           image: 'dwwd',
           tags: ['arcgis','node js','gps services']
        },
        {
           title: 'Vue.js injecting props',
           body: 'this is how to inject vue props into a component',
           image: 'dwwd',
           tags: ['vue','props','components','web development','web apps'] //remember to make tags from db into an array by splitting at ','
        }
      ],
      categories:['web development', 'arcgis','cyber security','partnerships'], //these don't come from the db
      search: '',
      tagList: [],
      pages: null,
      drawing: swiggle,
      mainlogo: slush,
      tags: tagsThumb,
      me: mepic,
    }
  },
  props: {
    post: Object
  },

  created(){

    var dataArray = []

    if(localStorage.getItem('data').length === 0){
      console.log('initial local store', localStorage.getItem('data'))

          let ref = fb.db.collection('articles')
          ref.get()
        .then(snapshot => {
          if (snapshot.empty) {
            console.log('No matching documents.');
            return;
          }  

          snapshot.forEach(doc => {  //this works for each doc
            console.log(doc.id, '=>', doc.data());

            let obj = {
              title: doc.data().title,
              body: doc.data().body,
              image: doc.data().image,
              tags: doc.data().tags.split(",")
            }
              dataArray.push(obj)
          })

        })
        .then((dataArray)=>{
          console.log('heres the data array to set in the local store',dataArray)
          localStorage.setItem('data', JSON.stringify(dataArray));
          console.log(localStorage)
        })
        .then(()=>{
              this.articles = JSON.parse(localStorage.getItem('data')) //push all data to this.articles
              console.log('checking value of this.articles',this.articles)
        })

        .catch(err => {
          console.log('Error getting documents', err);
        });

    }else{
        console.log('local store', localStorage)
      if(JSON.parse(localStorage.getItem('data').length !== undefined)){

        this.articles = JSON.parse(localStorage.getItem('data'))
        console.log('final articles',this.articles)
      }

    }
  },


  methods:{

    searchResultsByCat(val){
      let result = []
      for(let i = 0; i < this.articles.length; i++){
        for(let j = 0; j < this.articles[i].tags.length; j++){
            if (this.articles[i].tags[j].includes(val)){
                result.push(this.articles[i])
          }
        }
      }
       this.$router.push({name: 'Search', params: {data: result, search: val} })
    },

    gotoArticle(article){
      this.$router.push({name: 'Article', params: {data: article} })
    }

  }
}
</script>



The call to ref.get() seems to be returning a Promise , so it is an asynchronous operation that does not finish in the same cycle.

In other words, the callback to then has not run when you set your values. To fix your problem you should move the relevant lines into that callback as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM