Utilizing Vue Composables: Effectively Implementing Multiple Instances without State Sharing

In my VueJS application, I have a composable file that fetches information from an API and displays it in a table within two components simultaneously:

// Here is a basic example of the composable implementation:
export function useDatatable () {
  const table = ref({
    headers: [...],
    items: [],
    someValue: ''
  })

  async function getDocuments () {
    const { data } = await $axios.get('/documents')
    table.value.items = data
  }

  return {
    table,
    getDocuments
  }
}

Both document-table and document-billing-dialog components utilize this composable:

<template>
  <div>
    <document-table /> // Composable used here
    <document-billing-dialog /> // Composable also used here
  </div>
</template>

The usage of the composable in both components results in the unintentional behavior of functions being triggered twice and shared state values being interconnected. Is there a way to isolate instances of a composable for individual components?

Answer â„–1

Encountered a similar issue and came up with a solution involving separating the composable function.

// Here is a basic example of a composable that fetches information from an API 
// and displays it in a table using two components simultaneously

let tables = reactive([])

export default function useDatatable(datatableName) {
  tables[datatableName] = datatable()
  return tables[datatableName]
}

function datatable {
  const table = ref({
    headers: [...],
    items: [],
    someValue: ''
  })

  async function getDocuments() {
    const {
      data
    } = await $axios.get('/documents')
    table.value.items = data
  }

  return {
    table,
    getDocuments
  }
}

Initialize the composable with a specific name

<script>
  import useDatatable from '~/composables/useDatatable'
  // other imports

  export default defineComponent({
    setup () {
      const { table, getDocuments } = useDatatable('table-1')
    ...

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

How to keep the button on the page while using router-link in Vue 2?

I'm encountering an issue with my router-link in Vue 2. Within my parent component, I have a button that redirects users to a Create Post form when clicked. However, once redirected, the button remains visible in the Create Post form. How can I resolv ...

What is the best way to create a clickable background for a modal window?

I am looking to add a chatbox feature to my website and have been utilizing Bootstrap Modal for this purpose. My goal is to keep the modal open even when the user clicks outside of it, while still allowing them to interact with the background of the websi ...

Transform TypeScript class into an object

Is there a way to transfer all values from one typescript class, Class A, to another matching class, Class B? Could there be a method to extract all properties of Class A as an object? ...

Having trouble setting a value in a Vue.js variable

Upon assigning a value retrieved from the firebase collection, I encountered the following error message. Error getting document: TypeError: Cannot set property 'email' of undefined at eval (Profile.vue?5a88:68) Here is the code snippet in que ...

Using Internet Explorer to watch full-screen HTML 5 videos

I am in the process of developing my own HTML 5 Browser Player. Everything seems to be working well, except for getting the full screen feature to function properly in IE 10. Chrome, Safari, and Firefox are all doing great with it. Unfortunately, my JavaS ...

What is the reason behind genNewColor function's malfunction?

I'm having trouble with this code that is supposed to generate a random color. The CSS formatting works perfectly, but I suspect there might be an issue with the function itself. When I try to run the code, it doesn't produce any error messages â ...

What is the best way to incorporate this custom file upload button, created with vanilla JavaScript, into a React application?

Hey there! I have successfully implemented a custom file upload button using HTML, CSS, and JS. Now, I want to recreate the same design in React. Can someone guide me on how to achieve this in React? HTML Code: <br> <!-- actual upload which is h ...

Tips on preserving CSS modifications made in Chrome Developer Tools Inspector to .vue file

Currently, I am in the process of setting up a new workflow where my goal is to streamline my work by using the Chrome DevTools Inspector to save any CSS changes directly to my .vue file. While the DevTools Workspaces feature can achieve this, it involves ...

Discovering inner arrays within an outer array using the Plus function

Apologies if these questions seem basic in terms of JavaScript. Challenge 1. I am attempting to write code that can identify an inner array within an outer array, and the structure of the array looks something like this; var array = ['Bob', [ ...

Removing connected entries with pre middleware on mongoose

I currently have 3 different schemas: Building const BuildingSchema = mongoose.Schema({ address: { type: String, required: true }, numberOfFloors: { type: Number, default: 0 }, }); Apartment const RoomSchema = mongoose.Schema({ roomNumber: { type: ...

What is the process for determining the vertex position of geometry in three.js after applying translate, rotate, and scale transformations?

I've recently delved into the world of three.js. My current goal involves creating a curve within the scene and subsequently applying some transformations to it. The function responsible for generating the line is showcased below: var random_degree ...

What could be causing media queries to not update values even after being changed through JavaScript?

I have a simple navigation bar on my website, featuring links to different subpages. To enhance the user experience on mobile devices, I added a hamburger menu icon that is displayed on smaller screens. The links in the navigation bar are hidden using CSS ...

A collection of collections

Alright, listen up. I've got a JSON file with an array inside another array. Here's a snippet of the JSON file: { "keys": [ { "game": "Counter-Strike: Global Offensive", "price": "5", "listofkeys" ...

Unable to clear computed array property in Vue

Hello there! I am trying to modify a Vue computed array within a watch function, but unfortunately it is not getting emptied before pushing new values. The push operation works fine, however the truncation seems to be ineffective. Do you have any insight ...

Functionality of the button disabled in Firefox, despite working perfectly in Chrome

I have been developing a ReactJS application that is now live. Take a look at the deployed version to understand the issue I am facing. In Firefox, the Login button in the Inventory Login section doesn't seem to be working as expected. Despite having ...

Having trouble getting the jQuery script to properly check file size in an HTML form before uploading?

I've created an HTML form with a jQuery script to verify the file size when the SAVE button is clicked. Despite my efforts, the check doesn't seem to be functioning properly in the HTML Form. Please assist me with this and thank you in advance ...

I am having difficulty creating grid-template-columns in Vue

When I placed my code in the style scoped section... This is the desired output that I'm aiming for: .user-grid{ display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); grid-gap: 1rem; } .user-car ...

react-router version 2.0 fails to direct traffic

I'm facing an issue with a piece of code that I have modified from the react-router project page. Despite my modifications, it doesn't seem to work as expected. Configuration In my setup, I have created several simple react components: var Ind ...

What is the best method for modifying an array variable?

I am working with a variable array named data for my IGcombobox datasource. I need to update the array when I click on my #select element, but the current code is not changing the variable. Is there a way to achieve this without using PHP? <div id="c ...

Changing the style of a single element in various components in Vue

I need to alter the design of a specific div that is used in different components within my Vue.js application. The #app div should have a padding of 172px only in the Hello.vue component, while it should remain at 0px in all other components. Is there a w ...