I have a chrome extension with the following webpack.config.js:
module.exports = {
mode,
entry: {
"content/content": [
"./src/js/content/content.js",
"./src/js/store.js",
"./src/js/content/overlay/style.scss",
],
"background/background": [
"./src/js/background/utils.js",
"./src/js/background/background.js",
],
"overlay/overlay": "./src/js/content/overlay/index.js",
"popup/popup": "./src/js/content/popup/index.js",
},
looking at
Shared vuex state in a web-extension (dead object issues)
https://github.com/xanf/vuex-shared-mutations
Adding a wrapper around browser local storage:
browserStore.js
import browser from "#/js/browser";
export function getStorageValue(payload) {
return new Promise((resolve) => {
browser.storage.local.get(payload, (items) => {
if (items) {
resolve(items);
}
});
});
}
export function setStorageValue(payload) {
return new Promise((resolve) => {
browser.storage.local.set(payload, (value) => {
resolve(value);
});
});
}
In "./src/js/content/popup/firstpage/store/index.js" vuex store is defined as:
import Vue from "vue";
import Vuex from "vuex";
import "es6-promise/auto";
import createMutationsSharer from "vuex-shared-mutations";
import dummyData from "./dummyData";
import { getStorageValue, setStorageValue } from "#/js/store";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
chromePagesState: {
allSections: [],
},
},
getters: {
...
},
mutations: {
setChromePagesState(state, value) {
...
},
// this function is to be called from a content script
addWhiteListedItem(state, item) {
// state not initialized here
state.chromePagesState.allSections[0].itemSectionCategory[0].tasks.splice(
0,
0,
item
);
},
...
}
actions: {
async saveChromePagesState({ state }) {
// Save only needed fields
let data = {
...
};
await setStorageValue({ inventoryData: JSON.stringify(data) });
},
async loadChromePagesState({ commit }) {
const json = await getStorageValue("inventoryData");
// json always an empty object
commit(
"setChromePagesState",
Object.keys(json).length === 0 && json.constructor === Object
? json
: dummyData
);
},
async loadChromePagesStateBrowser({ commit }) {
browser.runtime
.sendMessage({ type: "storeinit", key: "chromePagesState" })
.then(async (chromePagesState) => {
const json = await getStorageValue("inventoryData");
commit(
"setChromePagesState",
Object.keys(json).length === 0 && json.constructor === Object
? json
: dummyData
);
});
},
plugins: [
createMutationsSharer({
predicate: [
"addWhiteListedItem",
"loadChromePagesState",
"loadChromePagesStateBrowser",
],
}),
],
},
the background script has a listener; src/background/background.js:
browser.runtime.onMessage.addListener((message, sender) => {
if (message.type === "storeinit") {
return Promise.resolve(store.state[message.key]);
}
});
The content script that needs to make use of the shared store has an entry point in content.js:
import { initOverlay } from '#/js/content/overlay';
import browser from '#/js/browser';
browser.runtime.onMessage.addListener(function (request, _sender, _callback) {
// vue component gets created here:
if (request && request.action === 'show_overlay') {
initOverlay();
}
return true; // async response
});
initOverlay() creates a vue component in ./src/js/content/overlay/index.js:
import Vue from "vue";
import Overlay from "#/js/content/overlay/Overlay.vue";
import browser from "#/js/browser";
import { getStorageValue } from "#/js/store";
import store from "../popup/firstpage/store";
Vue.prototype.$browser = browser;
export async function initOverlay(lockScreen = defaultScreen, isPopUp = false) {
...
setVueOverlay(overlayContainer, cover);
...
}
function setVueOverlay(overlayContainer, elem) {
if (!elem.querySelector("button")) {
elem.appendChild(overlayContainer);
elem.classList.add("locked");
new Vue({
el: overlayContainer,
store,
render: (h) => h(Overlay, { props: { isPopUp: isPopUp } }),
});
}
}
Overlay.vue only needs to call a mutation (addWhiteListedItem) from store:
<template>
<button
#click="addToWhiteList()"
>White list!</button
>
</template>
<script>
import { mapState, mapMutations } from "vuex";
export default {
data() {
return {
};
},
computed: mapState(["chromePagesState"]),
methods: {
...mapMutations(["addWhiteListedItem"]),
addToWhiteList() {
console.log("addToWhiteList()");
let newItem = {
...
};
// store not defined fails with:
Uncaught TypeError: Cannot read property 'itemSectionCategory' of undefined
at Store.addWhiteListedItem (index.js:79)
at wrappedMutationHandler (vuex.esm.js:853)
at commitIterator (vuex.esm.js:475)
at Array.forEach (<anonymous>)
at eval (vuex.esm.js:474)
at Store._withCommit (vuex.esm.js:633)
at Store.commit (vuex.esm.js:473)
at Store.boundCommit [as commit] (vuex.esm.js:418)
at VueComponent.mappedMutation (vuex.esm.js:1004)
at eval (Overlay.vue?./node_modules/vue-loader/lib??vue-loader-options:95)
this.addWhiteListedItem(newItem);
}, 1500);
},
},
};
</script>
Why doesn't Overlay.vue "see" the state of store?
Flow:
enabling the extension injects a content script into a page
content script imports store object (that is not yet initialized)
upon clicking popup (/new tab) popup.js sends a message to the background script that also imports store and calls a mutation (that initializes state):
background.js
import store from "../content/popup/firstpage/store";
browser.runtime.onMessage.addListener((message, sender) => {
console.log("in background");
if (message.type === "storeinit") {
console.log("got storeinit message. Message key: ", message.key);
store.dispatch("loadChromePagesState");
console.log("current state in store:", JSON.stringify(store.state));
console.log(
"store.state[message.key]:",
JSON.stringify(store.state[message.key])
);
return Promise.resolve(store.state[message.key]);
}
});
now the store's state should be initialized and the mutation callable from the content script (vue-shared-mutations guarantees it)
Does export default new Vuex.Store mean that every script that imports the store gets a new instance with a default state that is not in sync with other imports?
As the error message suggests itemSectionCategory can not be found as it is expected to be an element of allSections[0]. However you never define index 0 of allSections before calling it.
So in short you need to either define allSections index 0 before using it, or make the index part optional and create it if it's not found.
Otherwise you could try one of the following solutions:
if you need to rely on index 0 being available, check if it is set before calling your function
!state.chromePagesState.allSections[0] ? [... insert initialize function call ...]
Maybe optional chaining could be another solution depending on what you use it for afterwards, for an example How to use optional chaining with array or functions?
Related
I'm having trouble figuring this out with the vuex store. I have a created a subscription form to be able to enter your email address and I want to make a post request to the backend api but the data is not showing when I console.log it. It only console.logs the item that has been dispatch to the store and when I'm trying to mutate the item to the state.emailAddress and try to get the data that to the POST I get an empty object. enter image description here
import Vue from 'vue';
import Vuex from 'vuex';
import axios from 'axios';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
pizzaItems: [],
shopCart: [],
choosePizzaSize: [],
total: 0,
deliveryCharge: 0,
emailAddress: '',
},
getters: {
deliveryCharge: state => state.deliveryCharge,
pizzaItems: state => state.pizzaItems,
shopCart: state => state.shopCart,
choosePizzaSize: state => state.choosePizzaSize,
checkOut: state => state.total,
},
mutations: {
Add_To_Cart(state, item) {
const shopItem = state.shopCart.find(x => x.id === item.id && x.size === item.size);
if (shopItem) {
shopItem.count += item.count;
} else {
state.shopCart.push(item);
}
},
Price_Total(state, total) {
state.total = total;
},
fetchProducts(state, products) {
state.pizzaItems = products;
},
fetchPizzasize(state, size) {
state.choosePizzaSize = size;
},
free_Shipping(state, freeshipping) {
state.deliveryCharge = freeshipping;
},
subScribeMail(state, item) {
state.emailAddress = item;
},
},
actions: {
fetchData({ commit }) {
axios.get('http://localhost:3000/saltbageproducts').then((response) => {
commit('fetchProducts', response.data.products);
commit('fetchPizzasize', response.data.pizzasize[0].pizzaSize);
})
.catch((err) => {
console.log(err);
});
},
addTocart(context, item) {
context.commit('Add_To_Cart', item);
},
priceCalculation(context, item) {
context.commit('Price_Total', item);
},
changeFreeshippingStatus(context, shipping) {
context.commit('free_Shipping', shipping);
},
emailCheckUp(context, item, state) {
context.commit('subScribeMail', item);
axios.post('http://localhost:3000/saltbagehome', {
email: state.emailAddress,
}).then((reponse) => {
console.log(reponse.data);
}).catch((err) => {
console.log(err);
});
},
},
modules: {
},
});
Acoording Vuex documentation;
Register actions on the store. The handler function receives a context
object that exposes the following properties:
{
state, // same as `store.state`, or local state if in modules
rootState, // same as `store.state`, only in modules
commit, // same as `store.commit`
dispatch, // same as `store.dispatch`
getters, // same as `store.getters`, or local getters if in modules
rootGetters // same as `store.getters`, only in modules
}
And also receives a second payload argument if there is one.
Then in your first parameter of your action u have the vuex context, there should be:
emailCheckUp(context, item) { ... }
instead of
emailCheckUp(context, item, state) { ... }
now to access to vuex context inside of your action, just:
emailCheckUp(context, item) {
context.commit('subScribeMail', item);
...
email: context.state.emailAddress,
...
}
In practice, they often use ES2015 argument destructuring to simplify the code a bit:
emailCheckUp({commit, state}, item) {
commit('subScribeMail', item);
...
email: state.emailAddress,
...
}
I have a vuejs component and a vuex store.
I would like to send data from vue component to vuejs store and then call a function in vuex that's push data to a db.
I get the data from currentUser (that works), but in vuex store I get the error: Cannot read property 'push' of null.
I run createPost that works but the data does not pushed to vuex store I think because the error above.
#vuejs component
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
import {
SET_NEWPOST,
ADD_TAGS,
SET_USERDATA,
SET_GENERAL
} from "#/store/posts/mutations";
methods: {
...mapMutations("posts", {
updateInformation: SET_NEWPOST,
setUserData: SET_USERDATA,
addGeneral: SET_GENERAL,
addTags: ADD_TAGS
}),
...mapActions("posts", {
create: "triggerAddProductAction"
}),
async createPost() {
this.updateInformation({
content: this.content,
url: this.newOne
});
this.updateUserData();
this.createOne();
}
}
vuex store
...
const state = {
products: []
}
const mutations = {
[addProduct]: (state, product) => state.products.push(product)
},
const actions: {
createUserProduct: async ({ commit, rootState }, product) => {
const userProductDb = new UserProductsDB(
rootState.authentication.user.id
);
const createdProduct = await userProductDb.create(product);
commit("addProduct", createdProduct);
},
triggerAddProductAction: ({ dispatch, state, commit }) => {
const post = state.newPost;
dispatch("createUserProduct", post);
}
}
Your format I believe is a little off. Try building the store like this. Remember that using arrow functions vs non-arrow functions can also have a side effect in what is being referenced.
Mostly what can be seen, is that I removed the const's, and placed it all in the object literal directly. I also remove the Destructuring of addProduct as it doesn't seem logical here.
const store = new Vuex.Store({
state: {
products: []
},
mutations: {
addProduct: (state, product) => {
state.products.push(product)
console.log('Added Product:', product)
console.log('products', state.products)
}
},
actions: {
async createUserProduct({ commit }, product) {
commit("addProduct", product);
}
}
});
new Vue({
el: "#app",
store,
mounted() {
this.$store.dispatch('createUserProduct', 1)
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.1.0/vuex.min.js"></script>
<div id="app"></div>
I think one of the main problems here is actually that you call mutations directly in your component. Mutations should always be called by actions and not directly. This is because mutations are synchronous and actions can be asynchronous. From Vuex docs:
On to Actions
Asynchronicity combined with state mutation can make your program very hard to reason about. For example, when you call two methods both with async callbacks that mutate the state, how do you know when they are called and which callback was called first? This is exactly why we want to separate the two concepts. In Vuex, mutations are synchronous transactions:
store.commit('increment')
// any state change that the "increment" mutation may cause
// should be done at this moment.
To handle asynchronous operations, let's introduce Actions.
That's why you should have a structure like this:
export const mutations = {
ADD_EVENT(state, event) {
state.events.push(event)
},
SET_EVENTS(state, events) {
state.events = events
},
SET_EVENTS_TOTAL(state, eventsTotal) {
state.eventsTotal = eventsTotal
},
SET_EVENT(state, event) {
state.event = event
}
}
export const actions = {
createEvent({ commit, dispatch }, event) {
return EventService.postEvent(event)
.then(() => {
commit('ADD_EVENT', event)
commit('SET_EVENT', event)
const notification = {
type: 'success',
message: 'Your event has been created!'
}
dispatch('notification/add', notification, { root: true })
})
.catch(error => {
const notification = {
type: 'error',
message: 'There was a problem creating your event: ' + error.message
}
dispatch('notification/add', notification, { root: true })
throw error
})
}
Check also this video out by vuemastery even featured on the official vuex docs: https://www.vuemastery.com/courses/mastering-vuex/intro-to-vuex/
I'm building a little vue.js-application where I do some post requests. I use the watch-method to whach for api changes which then updates the component if the post request is successfull. Since the watcher constantly checks the API I want to add the ._debounce method but for some reason it doesn't work.
here is the code:
<script>
import _ from 'lodash'
export default {
data () {
return {
cds: [],
cdCount: ''
}
},
watch: {
cds() {
this.fetchAll()
}
},
methods: {
fetchAll: _.debounce(() => {
this.$http.get('/api/cds')
.then(response => {
this.cds = response.body
this.cdCount = response.body.length
})
})
},
created() {
this.fetchAll();
}
}
</script>
this gives me the error: Cannot read property 'get' of undefined
Can someone maybe tell me what I'm doing wrong?
EDIT
I removed the watch-method and tried to add
updated(): {
this.fetchAll()
}
with the result that the request runs in a loop :-/ When I remove the updated-lifecycle, the component does (of course) not react to api/array changes... I'm pretty clueless
Mind the this: () => { in methods make the this reference window and not the Vue instance.
Declare using a regular function:
methods: {
fetchAll: _.debounce(function () {
this.$http.get('/api/cds/add').then(response => {
this.cds = response.body
this.cdCount = response.body.length
})
})
},
Other problems
You have a cyclic dependency.
The fetchAll method is mutating the cds property (line this.cds = response.body) and the cds() watch is calling this.fetchAll(). As you can see, this leads to an infinite loop.
Solution: Stop the cycle by removing the fetchAll call from the watcher:
watch: {
cds() {
// this.fetchAll() // remove this
}
},
I'm currently migrating an application I developed from redux to apollo. I'm following this example trying to implement apollo-link-state and apollo-cache-inmemory but I'm struggling to understand how their framework works. It would be great if someone could answer some questions, so here we go:
Use Case: Store modals information (basically wether it's open or not) in my cache memory
Here is my code:
// apollos.js
import { ApolloClient } from 'apollo-client';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { withClientState } from 'apollo-link-state';
import { HttpLink } from 'apollo-link-http';
import { ApolloLink } from 'apollo-link';
import { modalStateQuery } from "./common/queries/modal.query";
const httpLinkOptions = {
uri: 'http://localhost:8080/graphql',
};
const httpLink = new HttpLink(httpLinkOptions);
const cache = new InMemoryCache({
dataIdFromObject: o => o.id
});
const typeDefs = `
type Modal {
id: ID!
open: Boolean!
}
type Query {
modal(id: ID!): Modal
modals: [Modal]
}
`;
const defaults = {
modals: [
{
__typename: "Modal",
id: "login",
open: false
},
{
__typename: "Modal",
id: "signup",
open: false
}
]
};
const resolvers = {
Query: {
modal: (_, { id }, { cache }) => {
console.log("get modal");
try {
const data = cache.readQuery({ query: modalStateQuery.getOne, variables: { id } });
console.log("data", data);
} catch (e) {
console.log("error", e);
}
return null;
},
modals: (_, { }, { cache }) => {
console.log("Modal List Resolver"); // this is never logged
}
}
}
const stateLink = withClientState({
cache,
resolvers,
defaults,
typeDefs
});
const link = ApolloLink.from([stateLink, httpLink]);
const client = new ApolloClient({
link,
cache,
dataIdFromObject: o => o.id
});
export default client;
-
// modal.query.js
import gql from "graphql-tag";
export const modalStateQuery = {
getOne: gql`
query ModalState($id: String!) {
modal(id: $id) #client {
id
open
}
}`,
getAll: gql`
query {
modals #client {
id
open
}
}
`
};
-
// modal.js
// ...
// fetching both for test purposes
export default compose(
graphql(modalStateQuery.getOne, { name: "modal" }),
graphql(modalStateQuery.getAll, { name: "allModals" })
)(Modal);
Ok, now the questions:
The number one problem I'm having is with the modal($id: id) query. When I execute modalStateQuery.getAll the modals resolver is never called, but I still get the list I defined in defaults in my component. But when I execute modalStateQuery.getOne I always get the same error:
error Error: Can't find field modal({"id":"login"}) on object (ROOT_QUERY) {
"modals": [
{
"type": "id",
"generated": false,
"id": "login",
"typename": "Modal"
},
{
"type": "id",
"generated": false,
"id": "signup",
"typename": "Modal"
}
]
}.
at readStoreResolver (readFromStore.js:71)
at executeField (graphql.js:90)
at graphql.js:46
at Array.forEach (<anonymous>)
at executeSelectionSet (graphql.js:40)
at graphql (graphql.js:35)
at diffQueryAgainstStore (readFromStore.js:124)
at readQueryFromStore (readFromStore.js:37)
at InMemoryCache../node_modules/apollo-cache-inmemory/lib/inMemoryCache.js.InMemoryCache.read (inMemoryCache.js:84)
at InMemoryCache../node_modules/apollo-cache-inmemory/lib/inMemoryCache.js.InMemoryCache.readQuery (inMemoryCache.js:181)
What is this array it is showing to me? Why isn't there all the props I defined in defaults (like open: false)? Could it be something wrong with the way I create my defaults?
In the apollo-cache-inmemory docs it doesn't define any resolvers, it just says that you should query your data just like you are doing it in the backend, passing the variables.
Also, why does modalStateQuery.getAll works even though the resolver is never called? What if I do want that resolver to be called (Maybe I want to check my backend first to check permissions or smth)?
Another curious behavior I noticed: When executing the modal resolver, the id variable is always correct, even though I didn't explicitly pass it as variable in my component, but the Modal.js component does have an id props that I pass to it:
return <Modal id="login"><LoginForm /></Modal>;
It makes me believe that apollo already recognizes that the Modal.js is being called with an id prop and automatically passes it to the query as a variable. Is that correct? It does it for any variable?
Thanks!
I'm using vuex to manage the state in my application and doing one way binding with my form.
<script>
import { mapGetters } from 'vuex'
import store from 'vuex-store'
import DataWidget from '../../../../uiComponents/widget'
export default {
data () {
return {
isEdit: false,
msg: {
id: 0,
content: '',
isEnabled: false
}
}
},
components: {
DataWidget
},
computed: mapGetters({
messageId: 'messageId',
messageContent: 'messageContent',
isMessageEnabled: 'isMessageEnabled',
isMessageValid: 'isMessageValid'
}),
methods: {
onSave () {
store.dispatch('saveMessage', this.msg, { root: true })
if (this.isMessageValid) {
this.isEdit = !this.isEdit
}
}
},
created () {
this.msg.id = this.messageId
this.msg.content = this.messageContent
this.msg.isEnabled = this.isMessageEnabled
}
}
</script>
<b-form-textarea id="content" v-model="msg.content" :rows="3" required aria-required="true" maxlength="250"></b-form-textarea>
On load, the values on created() are not binded until I perform an action on the page or refresh the page.
I have tried mounted () hooked same thing.
My Vuex store (Message Module) looks like this:
const state = {
messageId: 0,
messageContent: '',
isMessageEnabled: false,
isMessageValid: true
}
const getters = {
messageId: state => state.messageId,
messageContent: state => state.messageContent,
isMessageEnabled: state => state.isMessageEnabled,
isMessageValid: state => state.isMessageValid
}
const actions = {
getMessage ({commit, rootGetters}) {
api.fetch('api/Preference/Message', rootGetters.token)
.then((data) => {
commit(types.MESSAGE_LOAD, data)
})
}
}
const mutations = {
[types.MESSAGE_LOAD] (state, payload) {
state.messageId = payload ? payload.id : 0
state.messageContent = payload ? payload.content : ''
state.isMessageEnabled = payload ? payload.enabled : false
}
}
export default {
state,
getters,
actions,
mutations
}
and I have a global action (action.js) the gets multiple data:
export const loadSetting = ({ commit, rootGetters }) => {
api.fetchAsync('api/Preference/all', rootGetters.token)
.then((data) => {
commit(types.MESSAGE_LOAD, data.message)
commit(types.HELPDESK_LOAD, data.helpDesk)
commit(types.VOLUME_LOAD, data.volumes)
commit(types.DOWNLOAD_LOAD, data.downloadService)
})
}
My api call:
async fetchAsync (url, token = '') {
let data = await axios.get(HOST + url, {
headers: {
'Authorization': 'bearer ' + token
}
})
return data
}
The problem is your'e calling an async method in Vuex but in the created method, you're treating it like a sync operation and expect to get a value.
You need to use the computed properties you created since they are reactive and will update on every change. In order to make the computed writeable change it to be like this:
computed: {
...mapGetters({
messageId: 'messageId',
isMessageEnabled: 'isMessageEnabled',
isMessageValid: 'isMessageValid'
}),
messageContent(){
get () {
return this.$store.getters.messageContent
},
set (value) {
//this is just an example, you can do other things here
this.$store.commit('updateMessage', value)
}
}
}
And change the html to use messageContent:
<b-form-textarea id="content" v-model="messageContent" :rows="3" required aria-required="true" maxlength="250"></b-form-textarea>
For more info refer to this: https://vuex.vuejs.org/en/forms.html