VueJS list rendering anomaly - javascript

I already read some similar topics about my problem, but still I can’t figure out, what can be the problem is.
Long story short, I have an array of objects, and these objects also have an array, called “messages”. The parent object has some additional data, and my problem is caused by the child array, the messages.
The problem is:
The messages array is filled up by the server. After it, I successfully render a list of it’s content, show it on the web page, so far so good. But as soon as a new data arrives from the server, the rendered list is not updating itself. I checked the array’s content via the Vue dev plugin, and the new message was there, but the rendered list still remained in it’s original state.
The twist in the story is, that I created a simple test array, which is very similar to the original one, and also rendered on the page. When a new message arrives, I push it to both of them, and to my surprise, each one is updating itself perfectly. For the sake of curiosity, I commented out the test array rendering, and believe it or not, the original array does not update itself anymore on the page. After I remove the commented test array render, both of them works again.
The vue component:
/**
* Root
*/
import Vue from 'vue'
import axios from 'axios'
import inputComponent from './chat/input.vue'
new Vue({
el: '#chat-root',
components: { inputComponent },
data() {
return {
userID: document.getElementById('user').value,
ready: false,
roomID: "",
roomInstances: [],
test: [
{
messages: []
}
],
pollTime: 5000
}
},
created() {
axios.get('chat/init')
.then(resp => {
this.roomID = resp.data.roomList[0]._id
this.roomInstances = resp.data.roomList
this.fetchMessagesFromServer()
this.poll()
this.heartBeat()
}).catch(err => console.log(err))
},
computed: {
getMessages() {
return this.roomInstance.messages
},
roomInstance() {
return this.roomInstances.filter(i => i.id = this.roomID)[0]
}
},
methods: {
setRoom(id) {
if (this.roomID === id)
return
this.roomID = id
},
fetchMessagesFromServer() {
axios.get(`chat/get/${this.roomID}`)
.then(resp => {
this.roomInstance.messages = resp.data.messages
this.ready = true
}).catch(err => console.log(err))
},
heartBeat() {
setInterval(() => axios.get(`heartbeat/${this.userID}`), this.pollTime - 1000)
},
poll() {
axios.create({ timeout: this.pollTime })
.get(`poll/${this.userID}`).then(resp => {
if (resp.data.data) {
this.roomInstance.messages.push(resp.data.data.message)
this.test[0].messages.push(resp.data.data.message)
}
this.poll()
}).catch(err => console.log(err))
}
}
})
Template:
extends base
block scripts
script(src="/dist/chat.bundle.js")
block content
#chat-root(style="margin-top: 50px" v-cloak)
// Hack! Supposed to be an axios request?
input(v-if="false" id="user" value=`${user._id}`)
input-component(:room="roomID")
p {{ roomID || "Whoo hooo hoooo!" }}
span(v-for="room in roomInstances" #click="setRoom(room._id)") {{ room.name }} |
div(v-if="ready")
div(v-for="message in getMessages")
p {{ message }}
hr
div(v-for="fe in test[0].messages")
p {{ fe }}

For one, you are not finding the roomInstance correctly in the function for that computed property. You should just use the find method and return i.id === this.roomID in the callback instead of i.id = this.roomID:
roomInstance() {
return this.roomInstances.find(i => i.id === this.roomID);
}
The other issue might be when you are setting roomInstance.messages in the axios.get().then callback. If roomInstance.messages is undefined at that point, you'll need to use the Vue.set method (aliased on the Vue instance via this.$set) in order to make that property reactive:
this.$set(this.roomInstance, 'messages', resp.data.messages)
Here's the Vue documentation on Change Detection Caveats.

Related

Vue: Access values over api (nested)

Hi Stackoverflow Community,
In my template I try to show data which I receiver over an api call. When I log the api get response this is what I receive:
Now I try to show the data in location with the following code:
{{ userdetails.location.location_name }}
My script looks like this:
data() {
return {
userdetails: [],
};
},
methods: {
getUserData() {
DataService.getUserById()
.then((response) => {
this.userdetails = response.data;
console.log(response);
})
...
created() {
this.getUserData();
},
The strange thing is, I can see the location_name in my application. But I also receive an error:
I think I made somewhere a mistake, but I can't find it. Do you have any ideas what I am doing wrong?
Thank you in advance for all your tipps!
At the start, when the template tries to access userdetails.location.location_name, it is an empty list, so you will see the error. Only once the DataService updated userdetails will the nested properties exist.
The easiest way to prevent this is to start out with userdetails as something which is 'falsey' and then use v-if to determine whether to render:
<div v-if="userdetails">{{userdetails.location.location_name}}</div>
data() {
return {
userdetails: undefined,
};
},
Note however that if your DataService could ever return a dict which doesn't have the location property, you will need to do more testing in v-if to determine if it can be rendered.

Vue updates data without waiting for state file to update it

When the page is being loaded for the first time, vue component is not waiting for my custom store file to process it. I thought it might fix it with promises but I am not sure on how to do so on functions that do not really require extra processing time.
I am not including the entire .vue file because I know it surely works just fine. My store includes couple of functions and it is worth mentioning it is not set up using vuex but works very similarly. Since I also tested what causes the issue, I am only adding the function that is related and used in MainComp.
Vue component
import store from "./store";
export default {
name: "MainComp",
data() {
return {
isLoading: true,
storageSetup: store.storage.setupStorage,
cards: Array,
};
},
created() {
this.storageSetup().then(() => {
this.cards= store.state.cards;
});
this.displayData();
},
methods: {
displayData() {
this.isLoading = false;
},
}
My custom store.js file
const STORAGE = chrome.storage.sync;
const state = {
cards: []
};
const storage = {
async setupStorage() {
await STORAGE.get(['cards'], function (data) {
if (Object.keys(data).length === 0) {
storage.addToStorage('ALL');
// else case is the one does not work as required
} else {
data.cards.forEach((elem) => {
// modifies the element locally and then appends it to state.cards
actions.addCard(elem);
});
}
});
}
};
export default {
state,
storage
};
Lastly, please ignore the case in setupStorage() when the length of data is equal to 0. If there is nothing in Chrome's local space, then a cards is added properly(state.cards is an empty array every time the page loads). The problem of displaying the data only occurs when there are existing elements in the browser's storage.
How can I prevent vue from assuming cards is not an empty array but instead wait until the the data gets fetched and loaded to state.cards (i.e cards in MainComp)?
Sorry if the problem can be easily solved but I just lost hope of doing it myself. If any more information needs to be provided, please let me know.
Your main issue is that chrome.storage.sync.get is an asynchronous method but it does not return a promise which makes waiting on it difficult.
Try something like the following
const storage = {
setupStorage() {
return new Promise(resolve => { // return a promise
STORAGE.get(["cards"], data => {
if (Object.keys(data).length === 0) {
this.addToStorage("All")
} else {
data.cards.forEach(elem => {
actions.addCard(elem)
})
}
resolve() // resolve the promise so consumers know it's done
})
})
}
}
and in your component...
export default {
name: "MainComp",
data: () => ({
isLoading: true,
cards: [], // initialise as an array, not the Array constructor
}),
async created() {
await store.storage.setupStorage() // wait for the "get" to complete
this.cards = store.state.cards
this.isLoading = false
},
// ...
}

want to show updated status value in another component

i want to watch when a mutation called and updated a status. i make a component to show database table count when api called.
this is my store i wrote
const state = {
opportunity: ""
}
const getters = {
countOpportunity: state => state.opportunity
}
const actions = {
// count opportunity
async totalOpportunity({ commit }) {
const response = await axios.get(count_opportunity)
commit("setOpportunity", response.data)
},
}
const mutations = {
setOpportunity: (state, value) => (state.opportunity = value)
}
i want to show this getter value when this mutation called in another component name Opportunity.vue file.
i showed database count values in file name Dashboard.vue
i wrote it like this.
computed: {
...mapGetters(["countOpportunity"])
},
watch: {},
mounted() {
//do something after mounting vue instance
this.$store.watch(() => {
this.$store.getters.countOpportunity;
});
},
created() {
this.totalOpportunity();
},
methods: {
...mapActions(["totalOpportunity"])
}
and showed my view like this.
<div class="inner">
<h3>{{ countOpportunity }}</h3>
<p>Opportunities</p>
</div>
when api called and count increase shows my mutations. but my view value not updated (countOpportunity). any one can help me to fix this.
The issue here (most likely) is that the value of response.data is an object or an array. You've initially defined opportunity as '' which is not an observable object or array. You have 2 choices:
Redefine it as an empty object or array, depending on the response:
opportunity: [] // or {}
Otherwise, use Vue.set() to apply reactivity when changing it:
(Vue.set(state, 'opportunity', value))

Vuex Mutation running, but component not updating until manual commit in vue dev tools

I have a vue component that I can't get to update from a computed property that is populated from a service call.
Feed.vue
<template>
<div class="animated fadeIn">
<h1 v-if="!loading">Stats for {{ feed.name}}</h1>
<h2 v-if="loading">loading {{ feedID }}</h2>
</div>
</template>
<script>
export default {
data: () => {
return {
feedID: false
}
},
computed: {
feed(){
return this.$store.state.feed.currentFeed
},
loading(){
return this.$store.state.feed.status.loading;
}
},
created: function(){
this.feedID = this.$route.params.id;
var fid = this.$route.params.id;
const { dispatch } = this.$store;
dispatch('feed/getFeed', {fid});
}
}
</script>
That dispatches 'feed/getFeed' from the feed module...
feed.module.js
import { feedStatsService } from '../_services';
import { router } from '../_helpers';
export const feed = {
namespaced: true,
actions: {
getFeed({ dispatch, commit }, { fid }) {
commit('FeedRequest', {fid});
feedStatsService.getFeed(fid)
.then(
feed => {
commit('FeedSuccess', feed);
},
error => {
commit('FeedFailure', error);
dispatch('alert/error', error, { root: true });
}
)
}
},
mutations: {
FeedRequest(state, feed) {
state.status = {loading: true};
state.currentFeed = feed;
},
FeedSuccess(state, feed) {
state.currentFeed = feed;
state.status = {loading: false};
},
FeedFailure(state) {
state.status = {};
state.feed = null;
}
}
}
The feedStatsService.getFeed calls the service, which just runs a fetch and returns the results. Then commit('FeedSuccess', feed) gets called, which runs the mutation, which sets state.currentFeed=feed, and sets state.status.loading to false.
I can tell that it's stored, because the object shows up in the Vue dev tools. state.feed.currentFeed is the result from the service. But, my component doesn't change to reflect that. And there is a payload under mutations in the dev tool as well. When manually commit feed/feedSuccess in the dev tools, my component updates.
What am I missing here?
In the same way that component data properties need to be initialised, so too does your store's state. Vue cannot react to changes if it does not know about the initial data.
You appear to be missing something like...
state: {
status: { loading: true },
currentFeed: {}
}
Another option is to use Vue.set. See https://vuex.vuejs.org/guide/mutations.html#mutations-follow-vue-s-reactivity-rules...
Since a Vuex store's state is made reactive by Vue, when we mutate the state, Vue components observing the state will update automatically. This also means Vuex mutations are subject to the same reactivity caveats when working with plain Vue
Hey for all the people coming to this and not being able to find a solution. The following was what worked for me:
Declaring base state:
state: {
mainNavData: [],
}
Then I had my action which is calling the now fixed mutation:
actions : {
async fetchMainNavData({ commit }) {
var response = await axios.get();
commit('setMainNavData', response));
},
};
Now my mutation is calling this updateState() function which is key to it all
mutations = {
setMainNavData(state, navData) {
updateState(state, 'mainNavData', navData);
},
};
This is what the updateState function is doing which solved my issues.
const updateState = (state, key, value) => {
const newState = state;
newState[key] = value;
};
After adding updateState() my data reactively showed up in the frontend and I didn't have to manually commit the data in Vue tools anymore.
please note my store is in a different file, so its a little bit different.
Hope this helps others!
Sometimes updating property that are not directly in the state is the problem
{
directprop: "noProblem",
indirectParent: {
"test": 5 // this one has a problem but works if we clone the whole object indirectParent
}
}
but it is a temporary solution, it should help you to force update the state and discover what is the real problem.

Updating data from Vuex get a infinite loop in watcher

I have a "dumb" component that just get props from a parent. The user can change a selector which fires an action (using Vuex) to get new data. When this new data has been received I want to pass it to the child and re-render that component with the new data. Unfortutalely I keep getting this warning in my watcher. Please help :slight_smile:
export default {
name: 'bubbles',
props: {
awesomeData: {
type: Array,
required: true
}
},
data () {
return {
title: 'Best component ever'
}
},
watch: {
awesomeData (newData) {
console.log('hello world')
this.refreshSomethingAwesome(newData)
}
},
methods: {
refreshSomethingAwesome (newData) {}
}
}
s
101 hello world
[Vue warn]: You may have an infinite update loop in watcher with expression "awesomeData"
I'm trying a solution pretty much exactly the same as this: Vuex Examples
But can't seem to get it working... hmmm
Found out the reason I was getting the loop was because I was actually trying to sort mutable data from the property (thought it was immutable)
let options = {
children: newData.sort((a, b) => a.value - b.value)
}
I changed it to something like:
const sortedNewData = [...newData].sort((a, b) => a.value - b.value)
let options = {
children: sortedNewData
}
Note: To prevent this across my app, I might wrap my initial state in a Map from immutable.js
import { Map, fromJS } from 'immutable'
const initialState = Map({
awesomeData: fromJS([])
})
Helpful article: alligator.io

Categories

Resources