Utilizing Vue Composition API for Implementing Global State Management among Components

Recently, I attempted to utilize the Vue Composition API for global state management. For instance, I created a file named useLoading.js to handle loading flags.

useLoading.js

import { reactive, toRefs } from '@vue/composition-api'

export default () => {
  const state = reactive({
    isLoading: false
  })

  const setIsLoading = (loading) => {
    state.isLoading = loading
  }

  return {
    ...toRefs(state),
    setIsLoading
  }
}

Subsequently, I designed Component A, where the setIsLoading function is triggered upon clicking a button.

ComponentA.vue

<template>
  <div @click="showLoading" />
</template>

<script>
import useLoading from '@/composable/useLoading'

export default {
  setup () {
    const { setIsLoading } = useLoading()

    function showLoading () {
      setIsLoading(true)
    }

    return {
      showLoading
    }
  }
}
</script>

In addition, there is also Component B which displays a <div> based on the value of isLoading being true.

ComponentB.vue

<template>
  <div v-if="isLoading" />
</template>

<script>
import useLoading from '@/composable/useLoading'

export default {
  setup () {
    const { isLoading } = useLoading()

    return {
      isLoading: isLoading
    }
  }
}
</script>

However, I encountered an issue where the value of isLoading in ComponentB.vue was not updating (non-reactive). Strangely, it did react to changes when manipulated in ComponentA.vue.

I suspect that my implementation of using the Composition API as global state might be flawed. Any assistance would be greatly appreciated.

Thank you!

Answer №1

UPDATE

I just discovered that I need to remove the state from the export function. Including it in the export function will lead to the creation of additional states when called in a different location. This will result in the state not being synchronized between components.

import { reactive, toRefs } from '@vue/composition-api'

const state = reactive({
    isLoading: false
})

export default () => {

  const setIsLoading = (loading) => {
    state.isLoading = loading
  }

  return {
    ...toRefs(state),
    setIsLoading
  }
}

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 are some methods for saving HTML form data locally?

Creating an HTML form and seeking a solution for retaining user data even after closing and reopening the window/tab. Utilizing JavaScript cookies or HTML 5 local storage would require writing code for every input tag, which could be time-consuming especi ...

Experiencing an inexplicable blurring effect on the modal window

Introduction - I've implemented a feature where multiple modal windows can be opened on top of each other and closed sequentially. Recently, I added a blur effect that makes the background go blurry when a modal window is open. Subsequently opening an ...

Node.js refusing to acknowledge the get request handler for the homepage of the website

My Node.js server setup is quite simple: const express = require('express'); const app = express(); const http = require("http"); const path = require('path'); const favicon = require('serve-favicon'); // Public fil ...

"Exploring the New Features in React-Native 16 Alpha 12: Updating Prop Types

Upon creating a new project, my Expo XDE issued the following warning: 1:37:35 PM Warning: checkPropTypes has been moved to a separate package. React.checkPropTypes is no longer supported and will be completely removed in React 16. Use the prop-types ...

What is the best way to show inline icons within menu items?

Issue Upon selecting an option from the menu, I encounter a problem where the icon (represented by a question mark inside a speech bubble) appears on a different line than the text ("Question"). Fig. 1. Display of menu after selection with the icon and t ...

What is the process for retrieving the component along with the data?

As I work on compiling a list of div elements that require content from my firebase cloud storage, I find myself unsure about how to effectively run the code that retrieves data from firebase and returns it in the form of MyNotes. Consider the following: ...

What is the most effective method to retrieve the UserName using Javascript?

Can someone please explain to me the difference between using session["user"].name and session["user:name"]? // I don't understand why we have to put the user session into the JavaScript global space :( var session = { user: { "Id":"d675c ...

Is there a way to create an HTML select element where each option has a unique background color, and will display properly

I want to create multiple HTML select elements with unique background colors for each option: <select runat="server" id="select"> <option value="A">White</option> <option value="B">Red</option> <option value="C">Yellow& ...

Applying a CSS transition to transform properties excluding rotation effects

I'm looking to apply a transitional animation to an element's transform property without affecting the rotation. Here is the code snippet: <html> <head> <link rel="stylesheet" href="style.css"> <script src="script.js ...

Can a library be developed that works with both Java and JavaScript/TypeScript?

I specialize in Angular development. Our front- and backend both contain specialized calculation methods that work like magic. Although the classes are the same, any bugs found in the calculations have to be fixed separately in two different projects. Is ...

Best practice for triggering an Axios post request within a ReactJS application

My form is set up to store data in the state for sending to the backend server. I'm using the handleSubmit function and useEffect hook to handle the form, where handleSubmit ensures validation before submission, and useEffect checks for errors and log ...

Streamline the process of sorting through 2 arrays

Is there a more concise and elegant way to achieve the same functionality as my current method? I am looking for a shorter solution to create an array of items that haven't been used in the form previously, which are then used to populate a select dro ...

Executing JavaScript code within ASP.NET Visual Basic

My current web application uses jQuery and JavaScript, but I want to add more features that are supported in ASP.net VB. However, I am unsure if the JavaScript can run after the VB code. Essentially, I would like the web app to follow this sequence: ...

Add JSON elements to an array

Looking for help! {"Task": [Hours per Day],"Work": [11],"Eat": [6],"Commute": [4],"Sleep": [3]} Need to add these items to a jQuery array. I've attempted using JSON.parse without success. Typically, I can push parameters as follows: MyArr.push([& ...

Is there a way to stop Bootstrap from automatically bolding the font?

When testing this simple example without the bootstrap link, everything seems to be working correctly: Hovering over any word changes its color to red, and when hovering away it returns to black. But as soon as the bootstrap link is included, the text bec ...

What could be the reason for the failure of JSON.parse in parsing the following JSON string: `{ "Search results: ":s"": "" }`?

What could be causing the failure of JSON.parse to parse the JSON string provided below? Is the JSON syntax incorrect? Interestingly, even though its custom JSON parser throws the same error as JSON.parse, https://jsonlint.com/ validates this string. JS ...

Display sibling element upon hovering with AngularJS

Within a single view, I have multiple instances of repeated content elements. Each content element contains an anchor element. My goal is to toggle a class on a sibling element within that specific content element when a user hovers over the anchor. For c ...

What is the reason for choosing the term "shadow" over "override" in JavaScript?

Despite my initial assumptions, I found myself unable to discover a definitive answer through numerous Google searches on this topic. This question pertains to the use of the class pattern in Ecmascript 6 and beyond. I initially believed that method over ...

What steps can I take to detect errors when generating a MongoDB ObjectId in Node.js?

var selectedCriteria = Mongoose.Types.ObjectId(payloadData.skillId), If an incorrect Id is passed, the following error message will be displayed: Error: Uncaught error: Argument passed in must be a single string of 12 bytes or a string of 24 hex charac ...