I'm getting this problem in vue trying to display a graphic with apexcharts? - vue.js

I work with vue and apexchart. I call the api with the async method, to make sure that I am showing the correct information. I'm using console.Log and the array is correct. So does anyone know what is happening here? Thanks.

Probably your graph is created before the data of your api arrives. Try this :
data: () => ({
series: null
options: { ... }
}),
async mounted() {
this.loaded = false;
try {
const res = await fetch(urlYandex);
const json = await res.json()
this.series = json.data[0].metrics[0];
this.loaded = true;
} catch (e) {
console.error(e);
}
},
your apexchart you add like this :
<apexchart :options="options" :series="series" v-if="loaded"></apexchart>

Related

Vuejs created and mounted doesn't work properly even if at the same level than methods

I'm experiencing a strange behaviour with created() and mounted() in Vue.js. I need to set 2 lists in created() - so it means those 2 lists will help me to create a third list which is a merge.
Here is the code :
// return data
created () {
this.retrieveSellOffers();
this.getAllProducts();
},
mounted () {
this.mergeSellOffersProducts();
},
methods: {
retrieveSellOffers() {
this.sellerId = localStorage.sellerId;
SellOfferServices.getAllBySellerId(this.sellerId)
.then((response) => {
this.sellOffers = response.data;
console.log("this.sellOffers");
console.log(this.sellOffers);
})
.catch((e) => {
console.log(e);
});
},
getAllProducts() {
ProductServices.getAll()
.then((response) => {
this.products = response.data;
console.log("this.products");
console.log(this.products);
})
.catch((e) => {
console.log(e);
});
},
mergeSellOffersProducts () {
console.log(this.products) // print empty array
console.log(this.sellOffers) // print empty array
for (var i = 0; i < this.sellOffers.length; i++) {
if (this.sellOffers[i].productId === this.products[i]._id) {
this.arr3.push({id: this.sellOffers[i]._id, price: this.sellOffers[i].price, description: this.products[i].description});
}
}
this.arr3 = this.sellOffers;
},
}
//end of code
So my problem is when I enter in mergeSellOffersProducts(), my 2 lists are empty arrays :/
EDIT :
This way worked for me :
async mounted() {
await this.retrieveSellOffers();
await this.getAllProducts();
this.mergeSellOffersProducts();
},
methods: {
async retrieveSellOffers() {
this.sellerId = localStorage.sellerId;
this.sellOffers = (await axios.get('link/api/selloffer/seller/', { params: { sellerId: this.sellerId } })).data;
},
async getAllProducts() {
this.products = (await axios.get('link/api/product')).data;
},
}
I think the reason is: Vue does not wait for the promises to resolve before continuing with the component lifecycle.
Your functions retrieveSellOffers() and getAllProducts() contain Promise so maybe you have to await them in the created() hook:
async created: {
await this.retrieveSellOffers();
await this.getAllProducts();
}
So I tried to async my 2 methods :
async retrieveSellOffers() {
this.sellerId = localStorage.sellerId;
this.sellOffers = (await axios.get('linkhidden/api/selloffer/', { params: { sellerId: '615b1575fde0190ad80c3410' } })).data;
console.log("this.sellOffers")
console.log(this.sellOffers)
},
async getAllProducts() {
this.products = (await axios.get('linkhidden/api/product')).data;
console.log("this.products")
console.log(this.products)
},
mergeSellOffersProducts () {
console.log("here")
console.log(this.sellOffers)
console.log(this.products)
this.arr3 = this.sellOffers;
},
My data are well retrieved, but yet when I enter in created, the two lists are empty...
You are calling a bunch of asynchronous methods and don't properly wait for them to finish, that's why your data is not set in mounted. Since Vue does not await its lifecycle hooks, you have to deal with the synchronization yourself.
One Vue-ish way to fix it be to replace your method mergeSellOffersProducts with a computed prop (eg mergedSellOffersProducts). Instead of generating arr3 it would simply return the merged array. It will be automatically updated when products or sellOffers is changed. You would simply use mergedSellOffersProducts in your template, instead of your current arr3.
If you only want to update the merged list when both API calls have completed, you can either manually sync them with Promise.all, or you could handle this case in the computed prop and return [] if either of the arrays is not set yet.
When you're trying to merge the 2 lists, they aren't filled up yet. You need to await the calls.
async created () {
await this.retrieveSellOffers();
await this.getAllProducts();
},
async mounted () {
await this.mergeSellOffersProducts();
},

Nuxt - Wait after async action (this.$store.dispatch)

I'm new to Nuxt and I'm facing an issue that I don't understand.
If i code something like:
const resp1 = await this.$axios.$post('urlCall1', {...dataCall1});
this.$axios.$post('urlCall2', {...dataCall2, resp1.id});
The resp1.id is properly set in the 2nd axios call => we wait for the first call to be completed before doing the 2nd one.
However, when I define asyn actions in my vuex store ex:
async action1({ commit, dispatch }, data) {
try {
const respData1 = await this.$axios.$post('urlCall1', { ...data });
commit('MY_MUTATION1', respData1);
return respData1;
} catch (e) {
dispatch('reset');
}
},
async action2({ commit, dispatch }, data, id) {
try {
const respData2 = await this.$axios.$post('urlCall2', { ...data });
commit('MY_MUTATION2', respData2);
} catch (e) {
dispatch('reset');
}
}
and then in my vue component I fire those actions like:
const resp1 = await this.$store.dispatch('store1/action1', data1);
this.$store.dispatch('store2/action2', data2, resp1.id);
resp1.id is undefined in action2.
I also tried managing promise the "old way":
this.$store.dispatch('store1/action1', data1).then(resp1 => this.$store.dispatch('store2/action2', data2, resp1.id))
The result is still the same => id = undefined in action2
Can you guys please tell me where I'm wrong ?
Thanks in advance.
Last note: the 2 actions are in different stores
Vuex doesn't allow multiple arguments, so you have to pass it through as an object, so it could look like:
this.$store.dispatch('store2/action2', { ...data2, id: resp1.id });
And then in the store:
async action2({ commit, dispatch }, { id, ...data }) {
try {
const respData2 = await this.$axios.$post('urlCall2', { ...data });
commit('MY_MUTATION2', respData2);
} catch (e) {
dispatch('reset');
}
}

AddEventListener DOM event Jest testing

I have one Users vue component and I am trying to test mounted() with addEventListener.
Users.vue
=========
mounted(){
let viewPort = document.getElementById("Users-list"); ----> Here I am getting null for addEventListener.
viewPort!.addEventListener("scroll", (e: any) => {
let result =
e.target.scrollHeight - e.target.scrollTop - e.target.clientHeight ===
0;
if (result) {
this.test = this.Offset + this.Limit;
this.response = this.GetDetails();
}
});
}
I have written spec for Users component and trying to test mounted() method with addEventListener.
But I am getting an error message cannot read property addEventListener of null.
Users.spec.ts
=============
describe('Users TestSuite', async () => {
let userWrapper: any;
let userObj: any;
beforeEach(() => {
userWrapper = shallowMount(Users, {
// attachTo: document.getElementById('Users-list'),
localVue,
i18n,
router
})
userObj = userWrapper.findComponent(Users).vm;
const mockAddeventListener = jest.fn().mockImplementation((event, fn) => {
fn();
})
document.getElementById = jest.fn().mockReturnValue({
scrollTop: 100,
clientHeight: 200,
scrollHeight: 500,
addEventListener: mockAddeventListener
})
expect(mockAddeventListener).toBeCalledWith('scroll', expect.anything());
});
it('should render Users page', () => {
expect(userObj).toBeTruthy();
});
I think the problem here might be u are creating the mock function after u are creating the component. Mounted method will be called when the wrapper is created so try to move the mock implementation above the wrapper statement.
Another sure way in which to make it work is before u create the wrapper set the body of the document like document.body.innerHTML = <div id="users-list"></div>. This will definitely work.
For both the above solutions make sure that they are above the wrapper statement.

VueJS data doesnt change on URL change

My problem is that when I go from one user page to another user page the info in component still remains from first user. So if I go from /user/username1 to /user/username2 info remains from username1. How can I fix this ? This is my code:
UserProfile.vue
mounted() {
this.$store.dispatch('getUserProfile').then(data => {
if(data.success = true) {
this.username = data.user.username;
this.positive = data.user.positiverep;
this.negative = data.user.negativerep;
this.createdAt = data.user.createdAt;
this.lastLogin = data.user.lastLogin;
data.invites.forEach(element => {
this.invites.push(element);
});
}
});
},
And this is from actions.js file to get user:
const getUserProfile = async ({
commit
}) => {
try {
const response = await API.get('/user/' + router.currentRoute.params.username);
if (response.status === 200 && response.data.user) {
const data = {
success: true,
user: response.data.user,
invites: response.data.invites
}
return data;
} else {
return console.log('Something went wrong.');
}
} catch (error) {
console.log(error);
}
};
Should I add watch maybe instead of mounted to keep track of username change in url ?
You can use watch with the immediate property, you can then remove the code in mounted as the watch handler will be called instead.
watch: {
'$route.params.username': {
handler: function() {
this.$store.dispatch('getUserProfile').then(data => {
if(data.success = true) {
this.username = data.user.username;
this.positive = data.user.positiverep;
this.negative = data.user.negativerep;
this.createdAt = data.user.createdAt;
this.lastLogin = data.user.lastLogin;
data.invites.forEach(element => {
this.invites.push(element);
});
}
});
},
deep: true,
immediate: true,
},
}
Your page is loaded before the data is retrieved it seems, you need put a "loading" property in the data and have a v-if="!loading" for your component then it will only render once the display is updated. Personally I would avoid watch if I can it is not great for performance of for fine grained handling.
Yes you should add wach on statement that contain user info.(you may have a problem to watch on object, so you can save user info in json, but im not sure). When user changing - call action, after recived response call mutation that should change a state, then watch this state.
And you might use better syntax to receive data from store. That is really bad idea call dispatch directly from your mouted hook, use vuex documentation to make your code better.

Get item from AsyncStorage in React Native

I have a list of companies in React Native.
When I click on one of those companies I get the url of the API that is used for selected company. Then I store it to AsyncStorage and then I show the login screen. The function is as follows:
selectCompany(data_url, e) {
AsyncStorage.setItem("data_url", JSON.stringify(data_url), () => this.props.login());
}
Then on login page if I click on sign in button I go to the onLogin function, the function is as follows:
onLogin: function() {
fetch(data.url + '/manager/api/v1/obtain-auth-token/', })
.then(function(body) {
return body.json();
}).then(function(json) {
.....
}).catch(function() {
....
});
},
And data.url comes from data.js file, and I try to get url from the data.js file as follows:
let data_url = AsyncStorage.getItem("data_url").then(json => JSON.parse(json));
module.exports = {
url: data_url,
.....
}
But it doesn't work. Any advice?
AsyncStorage is async, therefore data_url will not be defined until it's retrieved what its looking for, you would need to move the fetch into the promise thats returned from the get so it will run it once it's done getting the data. This might be one way you tackle it:
const data_url = () => AsyncStorage.getItem("data_url"); //change this into a function
module.exports = {
url: data_url,
.....
}
now inside your component...
onLogin: function() {
data.url().then((url) => {
fetch(JSON.parse(url) + '/manager/api/v1/obtain-auth-token/', })
.then(function(body) {
return body.json();
}).then(function(json) {
.....
}).catch(function() {
....
});
});
},
AsyncStorage.getItem is a promise and needs to await for response rather than accessing direct and the function calling it should be defined as async. Here is an example to retrieve from AsyncStorage..
export async function getAccessKey(){
let accessToken = await AsyncStorage.getItem(ACCESS_TOKEN);
return accessToken;
}