Exploring Vue.js: The Power of Components and Cache

After researching ways to 'cache' API fetched data in my application, I discovered that it can be easily achieved using localStorage or sessionStorage.

Although it functions well, I am interested in consolidating all cached data into a single JSON entry within localStorage.

The challenge arises when trying to structure the JSON tree without replacing existing items. Allow me to elaborate:

Within my dashboard, there are two components: one for loading categories and another for displaying the latest articles. Each component utilizes a distinct endpoint.

Here is an example of how I cache 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))
    }
  },

And here's an example of caching 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 setup creates separate entries in the sessionStorage:

https://i.stack.imgur.com/3WLoq.png https://i.stack.imgur.com/IsQQf.png

I aim to consolidate all data under a single item, let's call it 'zhc_cache', which can be updated as components load...

For instance: dashboard: { categories: { ...... }, articles: { ...... } }

I suspect there may be issues with the asynchronous function, but I have yet to identify the root cause,

Any assistance would be greatly appreciated :)

Thank you

Answer №1

If my understanding is correct, you are looking to create a single JSON object that includes both categories and data. In that case, I suggest creating an object called "zn_cache" where you can add both categories and articles.

//If you want to maintain both functions, set vuejs data variables (categories and articles) and assign them the data retrieved from the API
this.categories = data.categories
this.articles = data.articles

You can then combine these into a global object (please verify the syntax as I am not completely certain)

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

Finally, you can store this object for later use.

Answer №2

@antoinehenrio

this solution works perfectly! :)

check out the updated dashboard below:

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 class="row">
      <div class="col col-12"> 
        <Categories :categories=this.categories />
      </div>
      <div class="col col-12"> 
        <Recents :articles=this.articles />
      </div>
    </div>
    `
}

take a look at the outcome:

https://i.stack.imgur.com/IMzfb.png

I'll need to adjust the other views, but it shouldn't be too difficult now.

Thank you once again!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best method for storing a third-party image in cache?

Running my website, I aim to achieve top-notch performance scores using LightHouse. I have successfully cached all the images I created (Cache-Control: public, max-age=31536000). Unfortunately, third-party website images are not cached. How can I cache t ...

Can Vue.js be paired with pure Node.js as a backend without relying on Express?

After successfully building a project with both vue js and node js, specifically with express, I'm curious if it's feasible to solely utilize node js without frameworks like express. ...

`Finding the nodejs API route for displaying images from a database`

How can I successfully display an image from the database without getting a string of question marks instead? Click here to see the issue >>> When attempting to directly call the API using the provided link, the following result is returned: {&qu ...

What is the best way to check a configuration setting in vue.config.js from srcmain.ts?

I am updating my vue application to include code that will automatically redirect from HTTP to HTTPS when accessing the page. (I understand that configuring this in the webserver is a better practice, but it doesn't hurt to be extra cautious) if (loc ...

What are the steps to set up a MEVN project to run on an intranet using nginx?

As a newcomer to the world of Vue, Node, Express, and MongoDB API while using Nginx, I have a question about where to place the port configuration. Can anyone provide insight on this? My project consists of a "client" folder and a "server" folder, both co ...

The yarn cache occupies a significant amount of storage

Just a few minutes ago, I was completely shocked to discover that the Yarn cache located at /Users/user/Library/Caches/Yarn is consuming over 50GB of my precious disk space. Why are there so many packages stored on my computer? While I appreciate Yarn&apos ...

When setting up Vue.js for unit testing, the default installation may show a message stating that

Recently set up a fresh Vue project on Windows 7 using the VueJS UI utility. Unit testing with Jest enabled and added babel to the mix. However, when running "npm test" in the command line, an error is returned stating 'Error: no test specified' ...

The installation of vue-cli failed due to permission issues with error code EPERM in npm

I keep encountering an error message when I try to run npm install -g vue-cli: npm ERR! path C:\Users\End User\AppData\Roaming\npm\node_modules\vue-cli\node_modules\nan\package.json npm ERR! code EPERM ...

unable to transfer Vuex store information to the graph

Currently, I am facing an issue with passing my vuex store data into my apexcharts graph. Despite my efforts, it seems like the data is not being displayed correctly. Can anyone provide guidance on what I might be doing wrong? My main objective is to updat ...

What steps can be taken to encourage a client to download a file from a webpage that is password-protected?

I've encountered a challenge with my FTP server, as it is password protected and I want users to be able to download from it via a button on my website without revealing the password. Currently, I am using puppeteer to bypass the authentication proces ...

Establishing communication sessions with Express.js server and Vue.js client

I have encountered an issue with my project setup. I am utilizing an expressJS server to create a REST api server and a VueJS client using VueCLI. Folder Layout : .root ├── _server | ├── Files related to the server ├── _client | ├ ...

Is it more advantageous to create two distinct projects for the frontend and backend along with an API, or should I consolidate them into a

Asking for some guidance on a few queries I have. I've developed a backend node server with express & mongo to run specific tasks and store them in the database, along with creating an admin page using express & bootstrap. Everything is functioning s ...

What causes the ignoring of config.proxy in axios requests while working on a webpack project?

My objective I am aiming to make a request using [email protected] with full efficiency through an http proxy (squid). My project is built on Vue and uses the webpack template. I initialized it with vue init webpack proxytest The challenge Despite ...

Guide on extracting data from MongoDB using VueJs

After successfully retrieving data from MongoDB using NodeJS, I am encountering an issue where the fields inside each object in the array are empty when trying to display them on my HTML page. The data is being fetched and displayed correctly in Chrome, bu ...

Error occurs when using Express.js in combination with linting

https://www.youtube.com/watch?v=Fa4cRMaTDUI I am currently following a tutorial and attempting to replicate everything the author is doing. At 19:00 into the video, he sets up a project using vue.js and express.js. He begins by creating a folder named &apo ...

Tips for resolving the error message: 'The "path" argument must be a string. Received type undefined' that occurs when executing 'vue add vuetify'

After successfully creating a new app using 'vue create agenda', I proceeded to cd into the project folder and run 'vue add vuetify' to integrate Vuetify. However, I encountered an unexpected error. I attempted to search for solutions ...

The installation of npm was unsuccessful due to an error: npm encountered an invalid JSON response

Warning: Peer dependency overridden by npm. Found: [email protected] in node_modules/@ivan/data-insights/node_modules/bootstrap. Bootstrap@^3.3.7 from @ivan/[email protected] version 1.7.26. Could not resolve dependency because peer bootstrap@^4.3.1 nee ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...

Is there a way to differentiate between a browser application running on a local development server and an online staging server?

Is there a way to conditionally call a component only on the staging server and not on the local machine in Vue.js? <save-drafts-timer v-if="!environment === 'development'" /> ... data () { return { environment ...

Looking for an efficient method to initiate vagrant configuration seamlessly with just a click?

When setting up different VirtualBoxes on Linux, I rely on using vagrant. My objective is to simplify the process for my colleagues by allowing them to visit an intranet site where they can choose which VirtualBox they would like installed on their machin ...