What is the process for transferring data from a Firestore collection to the Vuex State in

My objective is to integrate a firestore collection with the Vuex state in order to utilize it across multiple pages. I attempted to follow this guide:
How to get collection from firestore and set to vuex state when the app is rendered?

After following the instructions in the post, I encountered an issue where either I overlooked something or the code provided was outdated. As a newcomer to Vuex, I may have made mistakes in the process without realizing.

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
const db = require('../components/fbInit')


Vue.use(Vuex)

const store = new Vuex.Store({
  state: {
    categories: []
  },
  actions: {
    fetchCategories({ commit }) {
      db.collection('one').get().then(querySnapshot => {
        if (querySnapshot.empty) {
          // eslint-disable-next-line no-console
          console.log('cannot find')
          //this.$router.push('/HelloWorld')
        } else {
          this.loading = false;
          var categories = [];
          querySnapshot.forEach(doc => {
            categories.push(doc.data());
          });

          commit("setCategories", categories);
        }
      });
    }
  },
  mutations: {
    setCategories(state, val) {
      state.categories = val;
    }
  }
});

store.dispatch("fetchCategories");

export default store;

One.vue

<template>
  <div class="flex-row justify-center ma-12">
    <ul>
      <li v-for="category in categories" :key="category.name">{{category.name}}</li>
    </ul>
  </div>
</template>

<script>
import { mapActions } from "vuex";
import { mapGetters } from "vuex";
// eslint-disable-next-line no-unused-vars

export default {
  computed: {
    categories() {
      return this.$store.state.categories;
    },

    ...mapGetters([])
  },
  methods: {
    ...mapActions(["fetchCatagories"])
  }
};
</script>

Although I successfully connected to firestore and displayed its contents, I encountered the following error: Uncaught TypeError: db.collection is not a function.

I have not been able to load my firestore collection into the Vuex store state as desired. Any assistance on resolving this issue would be highly appreciated, especially since I am still learning how to use Vuex.

TLDR; Objective: Retrieve firestore collection ('One'), Save it in Vuex state, Utilize Vuex store to access the data across multiple pages without redundant calls.

Answer №1

app/main.js

const appStore = new Vuex.Store({
....
getters: {
    items (state) {
        return state.items;
    }
},
....
});

Two.vue

export default {
....
    computed: {
        ...mapGetters(['items'])
    },
....
}

Answer №2

Perhaps the issue lies in the statement <const db = require('../components/fbInit')
. In a Firestore/Vue project that I manage, I define my database as follows:

import firebase from '../firebase';
const db = firebase.firestore();

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

Mastering the Art of Promises in RXJS Observables

After thoroughly researching SO, I stumbled upon numerous questions and answers similar to mine. However, I suspect that there might be gaps in my fundamental understanding of how to effectively work with this technology stack. Currently, I am deeply enga ...

The topic at hand pertains to a specific exercise featured in the well-known book Eloquent JavaScript

In this exercise, the final step is to create a recursive function that takes a joined list and an index as parameters. The function's purpose is to find the value in the object within the list at the specified index. The code I have written seems to ...

Tips for acquiring offspring who are exclusively not descendants of a particular node

Currently, I am utilizing jQuery and my goal is to access all elements of a specific type that are not children of a particular node type. For example, my Document Object Model (DOM) structure looks like this: <div id='idthatiknow'> & ...

Ways to verify if fields within an Embedded Document are either null or contain data in Node.js and Mongodb

I need to verify whether the elements in the Embedded Document are empty or not. For instance: if (files.originalFilename === 'photo1.png') { user.update( { userName: userName ...

Differences Between Android and JavaScript: Ensuring Library Validity

Validation in JS is provided by the validator library which can be found at https://www.npmjs.com/package/validator Is there an equivalent library for validation in Android? If so, what is the name of Android's library? ...

Styling the NavDrawer button and navigation bar in React Native Router Flux

Currently in React Native Router Flux, I have a working NavDrawer component that utilizes react-native-drawer. The default hamburger menu icon on the left side of the navigation bar is what is currently displayed, but I am looking to swap it out for a cust ...

Is it possible to have numerous HTML files and directories in Phonegap/Cordova along with plugins?

As I transform my web app from HTML to Cordova for enhanced device functionality, including background audio and other features, I'm encountering some challenges. Due to the original structure of my application, which consists of multiple HTML files, ...

What is the best way to display input fields only if the previous input has a valid value?

My challenge involves creating a form with 3 to 10 text input fields. Initially, the form will display only 3 inputs (minimum). I am looking for an efficient way to dynamically show additional input rows as each previous row is filled out with a valid val ...

Error: NgFor can only be used to bind to data structures that are iterable, such as Arrays. JSON arrays are

Encountering ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables like Arrays. *ngFor="let spec of vehicleSpecs" Tried various solutions and searched extensi ...

Guide on generating tabs with the power of Javascript and Jquery

Is it possible to create multiple tabs on a page using jquery or javascript, where clicking buttons on the menu slides in a new page without changing the URL? I already have the HTML and CSS prepared. div.tabContent.hide { display: none; } nav { bac ...

Retrieve the attribute value from an HTML element in a JSON response using JavaScript

I received a JSON request result containing a blogger post. // API callback posts( { "version": "1.0", "encoding": "UTF-8", "entry": { "title": { "type": "text", "$t": "Vimeo Embed Video Post" ...

Utilizing ReactJS useState to eliminate a className

Basically, I'm trying to remove a className from an element when a button is clicked. I've attempted to use useState hooks and a regular function, with the onClick event on the button triggering this function/setUseState. However, the className l ...

Changing a transparent div with overlays into a visual representation of its underlying background

I am curious to know if it is feasible to carry out the operation mentioned, given that JavaScript doesn't currently have access to the contents of certain objects, such as a Flash video player. I have explored various screenshot plugins, but none of ...

The global $root event in vue seems to be missing in action

I am working on a vue component that needs to communicate with the root vue instance through an event. The component, a dialog form, triggers the event using this.$root.$emit() while the root listens with this.$root.$on(). However, I am facing an issue whe ...

Guide on showcasing subnested arrays in Vue search component for Laravel

Experiencing difficulties in showcasing eloquent relational data using my vue.js search template, specifically when it comes to the customer->biller fields. The models.student_first_name renders successfully, however, when attempting to display models. ...

Utilizing jQuery's slice() and remove() functions, followed by triggering jQuery's isotope to reorganize

I have been working on a project for the website My goal is to display only 25 posts and rearrange the post divs (.dcsns-li) by calling Isotope again. Here is the code I am using: jQuery(window).load(function(){ var nPosts = jQuery(".dcsns-li").length ...

Preflight request denied due to access control failure. No 'Access-Control-Allow-Origin' header present

I am currently working on a Vue.js application that utilizes axios to send requests to an ApiGee Server. Below is the code snippet I am using to send requests to APIgee. const headers = { 'X-API-Key': 'randomKey123123' } ...

"Transferring a C# dictionary into a TypeScript Map: A step-by-step

What is the correct way to pass a C# dictionary into a TypeScript Map? [HttpGet("reportsUsage")] public IActionResult GetReportsUsage() { //var reportsUsage = _statService.GetReportsUsage(); IDictionary<int, int> te ...

Utilizing Bootstrap's nav-pills component within Vue.js 2 framework

The link to the jsfiddle is located here: https://jsfiddle.net/r6o9h6zm/2/ In my project, I have implemented bootstrap nav pills in vue js 2 to show data based on the selected tab. However, I am encountering an issue where all three rooms are being displa ...

Determining Marker Location Post Drag in Laravel-VUE Component

I have integrated vue-google-maps into my project and it is working well so far. My goal is to have a marker appear when a user searches and selects their area, and then they can drag the marker to the desired position. I have successfully made the marker ...