Importing local JSON files into Vuex state

I am looking to import data from a local JSON file into a state value setting within my Vue.js application.

store/index.js

import { createStore} from 'vuex'

export default createStore({
  state: {
    settings: {}
  }
})

assets/json/settings.json

{
  "theme": "dark",
  "loggedIn": true,
  "mobile": false,
}

I need the imported data to be reactive so that it can work with computed properties in my Vue components. Ideally, I would like to find a way to save changes back to the JSON file using something like fs. I am utilizing Vuex for managing the data across multiple components.

How can I assign the values from the JSON file to the state.settings variable? 😅

Answer â„–1

To import data from a json file, simply treat it like you would a js file.

You can then include this imported data in the state initialiser.

import settings from "./settings.json";
export default createStore({
  state() { // Note: state should be a function to create a state
    return {
       settings: settings
    }
  }
})

Make sure your js compiler options include:

"resolveJsonModule": true

The browser should not directly edit this file. Save changes using cookies, local storage, session storage, or by calling a webservice on your server.

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

Trouble with the display:none attribute in Firefox and Chrome

<tr style="height:5px" id="TRRSHeaderTrialBar" name="TRRSHeaderTrialBar" style='display:none'> <tr id="TREmail" name="TREmail" style="height:1px;" nowrap style='display:none'> Using the code snippet above to hide the bar w ...

Transform JSON data into XLSX format for all files with a .json extension within the specified directory

Dealing with the challenge of parsing multiple JSON files located in the same directory as the program's executable file, extracting specific elements from these files, and consolidating them into a single Excel file. For instance, there are several ...

What is the best way to change function.bind(this) to an arrow function in a react native application?

I am attempting to convert my function into an arrow function, but I keep encountering an error of undefined when passing props. <TextInput style={styles.input} value={formState.inputValues.title} onChangeText={textCh ...

Creating a dynamic HTML table using Vue 3

My table is not showing the data I'm fetching from my API. Even though I can see the data in my console.log, it's not populating the table. Could there be an issue with how I'm calling the data to display in the table? <template> < ...

The jquery methods might encounter an issue with an undefined object

I have been attempting to implement a function that triggers when the user reaches the bottom of the window, but TypeScript is flagging errors and mentioning potential undefined objects related to window.scrollTop(), height(), and document.height(). Even ...

Difficulty Communicating Recapcha 2 with the PHP Script

I am currently testing the installation of reCaptcha 2 with server-side verification using a form with one input field. My process involves sending the reCaptcha response via Ajax to a PHP page for verification. While I am able to capture the information p ...

Transferring a JSON object from an Android device to a server

I am having some difficulties sending JSON to an HTTP server in the following format: {"deviceID":3852883413434, "depth":2,"location":{"xCord":46.232, "yCord":42.4421},"size":3} Here is the code snippet I have written for Android, but it doesn't see ...

Converting a nested JSON array into a DataFrame using Spark

My task involves processing a json file that follows this schema: root |-- Header: struct (nullable = true) | |-- Format: string (nullable = true) | |-- Version: struct (nullable = true) | | |-- vfield: string (nullable = true) |-- Payload ...

The issue of invalid prop in Vue Utils

Having an issue with Vue Util Error: console.error [Vue warn]: Invalid prop: type check failed for prop "icon". Expected Object, Array, String, got Undefined In my parent component 'myComp', there is a global component Font Awesome n ...

What causes the non-reachable part of the ternary operator to be evaluated prior to updating the state with setTimeout?

Check out my latest code snippet for a react component that renders a massive component. While the huge component is still rendering, a loading indicator will be displayed. import * as React from "react"; import ReactDOM from "react-dom"; import {HUGECom ...

A guide to retrieving location markers from Firebase's real-time database and displaying them on a map view using Xcode and Swift

My objective is to replace the hardcoded array data with a download from Firebase Realtime Database and store it in either 4 separate arrays or an array of another array for each night club. The structure of the Firebase Realtime Database JSON can be foun ...

Storing and Retrieving Multiple Data with localStorage

I need assistance with modifying my code. I have an input field labeled "mail" and I am trying to store email addresses and corresponding IDs in local storage. The email address should be taken from the "mail" input field while the ID should increment each ...

How to efficiently pass multiple inputs from an HTML form to a controller in AngularJS using a single ng

Currently, I have multiple input text boxes in my HTML and I need to send their values to my controller to add them to an object. The challenge I'm facing is figuring out how to pass more than one value using just one ng-model. In my HTML code, I have ...

Encountering timeout issues with Next.JS fetch and Axios requests on Vercel production environment

I've been encountering an issue where I am unable to fetch a specific JSON data as it times out and fails to receive a response on Vercel deploy. The JSON data I'm trying to fetch is only 18KB in size and the fetch request works perfectly fine in ...

Tips for quietly printing a PDF document in reactjs?

const pdfURL = "anotherurl.com/document.pdf"; const handleDirectPrint = (e: React.FormEvent) => { e.preventDefault(); const newWin: Window | null = window.open(pdfURL); if (newWin) { newWin.onload = () => ...

Improving List performance with React.cloneElement

I am uncertain about the usage of React.cloneElement within a List component. Is it recommended to avoid using it, especially when dealing with a large number of elements in the list? Does React.cloneElement cause unnecessary re-renders that can be optimal ...

Error on Network: 400 BAD REQUEST in Ionic framework

I recently implemented push notifications successfully, but I am facing a network error with a 400 bad request when trying to access a specific API endpoint. The error message states: "NetworkError: 400 BAD REQUEST - https://apps.ionic.io/api/v1/app/77c3 ...

Error when accessing JSON property in Angular with Ionic 2: A Strange TypeError

I have implemented a provider in my Ionic project to fetch the user object from storage. Below is the code: import { Injectable } from '@angular/core'; import { Storage } from '@ionic/storage'; @Injectable() export class ApiProvider { ...

Acquiring the console log data from Firefox version 43 using Selenium, all without the use of any

Can Selenium retrieve the console.log from browsers like Firefox 43? If so, how can it be done? My settings are as follows: DesiredCapabilities capabilities = DesiredCapabilities.firefox(); LoggingPreferences logs = new LoggingPreferences(); logs.enable( ...

Exploring the power of Vue with Cypress testing and streamlining the development process

Currently, I am facing a challenge while trying to run my E2E tests on Gitlab using their CI/CD platform. The issue I'm encountering is the inability to have both my development server and Cypress running simultaneously in order for the E2E tests to ...