Home > other >  Vuejs, components and cache
Vuejs, components and cache

Time:05-04

i was looking for a way to 'cache' some API fetched data in my application, and find out it can simply be done with localStorage (or even sessionsStorage)

While it works fine, i'm looking for a way to have all the cached data in one localStorage entry (in JSON)

The problem is i can't figure out how to build the JSON tree without overriding previous item. Let me explain :

On my dashboard, I have two components, one that load categories, the other loading last articles. Each component uses a different endpoint.

this is how i set cache (for categories) :

methods: {
    async getCategories() {

      let response = await fetch('https://carreblanc.zendesk.com/api/v2/help_center/fr/categories.json', {
        method: 'GET',
        headers: zendeskHeaders,
      })

      if (response.status === 200) {
        let data = await response.json();
        this.categories = data.categories

        // Build cache
        let cacheData = []
        cacheData.push(data)
        sessionStorage.setItem('zhc_db_cat_cache', JSON.stringify(cacheData))
      }
      else {
        console.log("Something went wrong ("   response.status   ")");
        return Promise.reject(response);
      }
    },
    setUrl(url) {
      return decodeURI(url.substring(url.indexOf('-')   1))
    }
  },

for articles :

methods: {
    async getArticles() {

      let response = await fetch('https://carreblanc.zendesk.com/api/v2/help_center/fr/articles.json', {
        method: 'GET',
        headers: zendeskHeaders,
      })

      if (response.status === 200) {
        let data = await response.json();
        this.articles = data.articles
        
        // Build cache
        let cacheData = []
        cacheData.push(data)
        sessionStorage.setItem('zhc_db_art_cache', JSON.stringify(cacheData));
      }
      else {
        console.log("Something went wrong ("   response.status   ")");
        return Promise.reject(response);
      }
    },
    setUrl(url) {
      return decodeURI(url.substring(url.indexOf('-')   1))
    }
  },

this results in two entries in the sessionStorage :

enter image description here enter image description here

I want only one item, let's say 'zhc_cache', in which i can update data while components load..

for example : dashboard: { categories: { ...... }, articles: { ...... } }

I think there's something going on with the async function, but i can't figure it out,

any help will be appreciated :)

Thanks

CodePudding user response:

If i understand it correctly, you just want one JSON object with categories AND data? In that case, i think you should create an object ("zn_cache"), in which you add categories and articles

//If you want to keep both functions, just set vuejs data variables (categories and articles) and affect them the data you fetched from the api
this.categories = data.categories
this.articles = data.articles

Then you can create a global object with both (check the syntax I'm not 100% sure)

let dashboard = { 'categories' : this.categories, 'articles' : this.articles}

Then you can store this bad boy

CodePudding user response:

@antoinehenrio

works like a charm ;)

here is the dashboard now

const zendeskConfig = {
  categoriesEndpoint: 'https://carreblanc.zendesk.com/api/v2/help_center/fr/categories.json',
  articlesEndpoint: 'https://carreblanc.zendesk.com/api/v2/help_center/fr/articles.json'
};

import Categories from '/skin/frontend/carreblanc/revamp/js/zendesk/hc/components/dashboard/categories.js'
import Recents from '/skin/frontend/carreblanc/revamp/js/zendesk/hc/components/dashboard/recent-activity.js'

export default {
  components: {
    Categories,
    Recents
  },
  data() {
    return {
      categories: [],
      articles: [],
    }
  },
  methods: {
    getData() {
      Promise.all([
        fetch(zendeskConfig.categoriesEndpoint).then(res => res.ok && res.json() || Promise.reject(res)),
        fetch(zendeskConfig.articlesEndpoint).then(res => res.ok && res.json() || Promise.reject(res))
      ]).then(([resCategories, resArticles]) => {
        this.categories = resCategories.categories
        this.articles = resArticles.articles
        let cacheData = { dashboard: { 'categories' : this.categories, 'articles' : this.articles} }
        sessionStorage.setItem('zhc_db_cache', JSON.stringify(cacheData))
      })
    }
  },
  created() {
    this.getData()
  },
  template: `
    <div >
      <div > 
        <Categories :categories=this.categories />
      </div>
      <div > 
        <Recents :articles=this.articles />
      </div>
    </div>
    `
}

and the result :

enter image description here

I have to reconfigure the other views, but it should be easy now

Thanks again !

  • Related