Utilizing an asynchronous function in ES6 Vue.js and TypeScript

I'm currently working on optimizing my code for reusability, and I've decided to store multiple async functions in a separate file.

blog.ts


import db from '@/firebase/init'

async function fetchTags (uid) {
  const tags = db.collection('tags').where('blogId', '==', uid)
  const data = []

  await tags.get()
    .then(snapshot => {
      snapshot.forEach(doc => {
        console.log(doc.data())
        data.push(doc.data().tag)
      })
      return data
    })
    .catch(error => {
      console.log('Error fetching documents', error)
    })
}

export default fetchTags

anotherpage.vue

<script>
import { fetchTags } from '@/functions/blog'

mounted () {
  if (this.$route.params.blog) {
    this.blog = this.$route.params.blog
  }
  fetchTags(this.blog.uid)
}

An error message is returned stating that:

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in mounted hook: "TypeError: Object(...) is not a function"

found in

---> <EditBlog> at src/components/admin/admin/Blog/EditBlog.vue
       <CreateBlog> at src/components/admin/admin/Blog/CreateBlog.vue
         <LayoutDefault> at src/App.vue
           <Root>

If anyone knows of a guide that explains the correct way to import these functions, please share it with me.

Answer №1

When importing modules, make sure to match named exports with the correct import syntax. If you have a default export in your module, such as

import getTags from '@/functions/blog'
, you can use it without specifying a variable name.

To utilize named exports instead of default exports for multiple functions in one file, simply remove the default keyword from your function declaration. This allows you to selectively import specific functions by their names.

If you're interested in learning more about named exports versus default exports in ES6, check out this informative blog post here.

Take a look at an example of how a file (blog.ts) with multiple named exports would appear:

export async function getTags(uid) {
  // code here
}

export async function getLaundry(uid) {
  // additional code here
}

In another file where you want to import only specific functions, like getLaundry, you can do so using:

import { getLaundry } from '@/functions/blog'

Alternatively, if you need both functions imported, you can use:

import { getLaundry, getTags } from '@/functions/blog'

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

I'm looking to validate an input tag in HTML5 using JQuery. Can anyone help clarify this process for me?

New to JQuery and struggling with HTML5 input tag validation. On my page, I have an input tag like this: <input id="variazioneAnticipo" class="rightAlligned form-control" style="width:50%" type="number" step="0.01" /> and a button: <button id="va ...

Trigger a function when <a> is clicked, which will then increment the count by one and reflect this change in the database

The database generates the content of this div ordered by a count number called "cts". Whenever I click on the div, I want the "cts" number to increase by one, and then update the change in the database. This will result in the content changing accordingly ...

Is there a way to convert the instructions or code meant for webpack.config.js so that they can be applied to the vue.config.js file?

Having encountered an issue with vue-cli, I found out that instead of webpack.config.js, it uses a vue.config.js: const { defineConfig } = require('@vue/cli-service') module.exports = defineConfig({ transpileDependencies: true, }) After ins ...

What is the best way to retrieve the latest files from a Heroku application?

Having recently migrated my Discord Bot to Heroku, I faced a challenge with retrieving an updated file essential for code updates. I attempted using both the Git clone command and the Heroku slugs:download command with no success in obtaining the necessar ...

When retrieving HTML from the server, the scope values are not appearing as expected

UPDATE: After extensive testing of my code, I have gained a better understanding of what is not functioning correctly, prompting me to revise my previous inquiry. When browsing to the / directory in my local environment, my HTML file loads successfully. ...

The interpolated string type is not allowed to be utilized for indexing a record that has the identical type as the key

I'm attempting to utilize an interpolated string form to access a Record type using a key that should match the record's key type. Unfortunately, it doesn't appear to be functioning as expected. Here is a simple example: type TypeOfKey = `c ...

Combining Data in React Arrays

I have an array with different group types and I need to merge the results if the grouptype is the same. const locationss = [ { grouptype: "Name1", id: "1", servicetype: [ { name: "Morning", price: "5& ...

Learn the process of retrieving a file from server.js and showcasing it on an HTML page

I am currently developing a YouTube video downloader using express, HTML, and JavaScript, with plans to transition to Vue.js in the future. Here is a snippet of my code: Index.html <!DOCTYPE html> <html lang="en"> <head> & ...

How can I create a JSON output from my MySQL database that includes the total count of records per day for a Task entry?

I am looking to implement the JavaScript library called Cal-Heatmap (https://kamisama.github.io/cal-heatmap/) to create an Event style heatmap similar to GitHub's. The objective is to visualize the number of actions taken on each Task record in my Pr ...

Retrieve the URI data from the response object using Axios

Currently, I'm in the process of transitioning a node project from utilizing request.js to incorporating axios.js While using the request package, extracting URI data from the response object can be achieved like so: request(req, (err, response) =&g ...

What is the best way to establish a connection between a child and parent component using a click event?

I am working on a scenario where I have two components interacting with each other. The parent component features a button, and upon clicking this button, the child component is disabled while also opening up to display its own button for closing. How can ...

When an event is triggered in Angular Component, the object is not properly defined in the handler causing errors

While experimenting with createjs and angular, I encountered an issue when trying to update my stage after an image loads. It seems like there might be a problem related to Angular in this situation. Upon completion of the load event on the Bitmap object a ...

Unable to implement the checkCollision function within the Snake game using JavaScript

My latest project involves creating a Snake game using canvas in JavaScript. I've managed to set up most of the game, but I'm having trouble with the collision check. Whenever the snake hits itself or the wall, the game crashes because I can&apos ...

Error exporting a function in Node.js

As someone who is new to writing node.js modules, I have been working on a module in the following way, a.js var fs = require("fs") ; var util = require("util") ; var mime = require("mime") ; module.exports = { getDataUri: function (image, callback ) ...

"Utilize Tuple in TypeScript to achieve high performance programming

I've been delving into TypeScript, focusing on the tuple type. As per information from the documentation, here is the definition of a tuple: A tuple type is another form of Array type that precisely knows its element count and types at specific posi ...

Using JavaScript variables in CSS: a beginner's guide

My website features a typewriter effect, but I want the animation to match the length of the words exactly. I attempted using JavaScript variables in CSS, but unfortunately, it's not functioning properly. Could someone please advise me on how to remed ...

Error message while using Jest, ts-jest, and TypeScript with ES Modules import: module not found

Having difficulties getting Jest to work with a TypeScript project that uses ES modules and the import syntax. I originally wrote my project using commonjs, and the Jest tests ran fine. However, when I switched to ES Modules for learning purposes, Jest is ...

Aligning the Bootstrap 5 navbar dropdown to the right side

I'm having trouble getting a part of my navbar to align right in bootstrap 5. I've followed the new documentation, but I think I might be adding the text in the wrong place. Can someone assist me in moving my dropdown to the right side of the nav ...

Is it possible for me to pass a reference to a specific object's instance function?

Can JavaScript allow you to pass a function reference to a specific object's function, similar to what can be done in Java? Let's take a look at this code snippet: _.every(aS, function (value) { return exp.test(value); }); What if we want ...

Validation Express; the error variable is not defined in the EJS

Struggling with a perplexing issue that has been eluding me for quite some time now, I am hopeful that someone out there might be able to provide me with some guidance. The variable (error) that I am passing in the res.render{} object seems to be unattain ...