blink store data after change route - api

how can i avoid the data blink after update store data?
you can see the effect here:
https://drive.google.com/file/d/178raL6AJiC4bpIOImnaTKh6Yf9GruTCz/view?usp=sharing
component:
[...]
mounted() {
this.getIdeasFromBoard(this.$route.params.board_id);
},
[...]
store:
[...]
const actions = {
getIdeasFromBoard({ commit, dispatch }, board_id) {
apiClient
.get('/ideas/' + board_id)
.then((result) => {
console.log('success');
commit("SET_IDEAS_BOARD", result.data);
})
.catch(error => {
console.log('error' + error);
alert("You have failed to log in. Try again with another credentials.");
dispatch('auth/logout', null, { root: true });
this.$router.push({ name: "public" });
});
},
[...]
i've searched some simple tutorial about consuming api with error handling, but didnt find it.
thanks

It's because IDEAS_BOARD has the previous data until the new API call is completed. You would need to display a loader or a blank screen until the API call for the selected board is completed.
From actions, return a promise so that your component knows when is the call completed.
getIdeasFromBoard({ commit, dispatch }, board_id) {
return new Promise((resolve, reject) => {
apiClient
.get('/ideas/' + board_id)
.then((result) => {
console.log('success');
commit("SET_IDEAS_BOARD", result.data);
resolve()
})
.catch(error => {
console.log('error' + error);
alert("You have failed to log in. Try again with another credentials.");
dispatch('auth/logout', null, { root: true });
this.$router.push({ name: "public" });
reject()
});
})
},
In your .vue component,
async mounted () {
this.loading = true // some flag to display a loader instead of data
await this.$store.dispatch()
this.loading = false
}
There must be some other ways too like having this loading flag in the Vuex store. But it depends on you

Related

Call Vuex action from component after mutation is complete

I have a Vue component that calls a Vuex action in its create hook (an api.get that fetches some data, and then dispatches a mutation). After that mutation is completed, I need to call an action in a different store, depending on what has been set in my store's state... in this case, getUserSpecials.
I tried to use .then() on my action, but that mutation had not yet completed, even though the api.get Promise had resolved, so the store state I needed to check was not yet available.
Does anyone know if there is a 'best practice' for doing this? I also considered using a watcher on the store state.
In my component, I have:
created () {
this.getUserModules();
if (this.userModules.promos.find((p) => p.type === 'specials')) {
this.getUserSpecials();
}
},
methods: {
...mapActions('userProfile', ['getUserModules',],),
...mapActions('userPromos', ['getUserSpecials',],),
},
In my store I have:
const actions = {
getUserModules ({ commit, dispatch, }) {
api.get(/user/modules).then((response) => {
commit('setUserModules', response);
});
},
};
export const mutations = {
setUserModules (state, response) {
Object.assign(state, response);
},
};
Right now, the simple if check in my create hook works fine, but I'm wondering if there is a more elegant way to do this.
[1] Your action should return a promise
getUserModules ({ commit, dispatch, }) {
return api.get(/user/modules).then((response) => {
commit('setUserModules', response);
})
}
[2] Call another dispatch when the first one has been resolved
created () {
this.getUserModules().then(response => {
this.getUserSpecials()
})
}
Make your action return a promise:
Change:
getUserModules ({ commit, dispatch, }) {
api.get(/user/modules).then((response) => {
commit('setUserModules', response);
});
},
To:
getUserModules({commit, dispatch}) {
return new Promise((resolve, reject) => {
api.get(/user/modules).then((response) => {
commit('setUserModules', response);
resolve(response)
}).catch((error) {
reject(error)
});
});
},
And then your created() hook can be:
created () {
this.getUserModules().then((response) => {
if(response.data.promos.find((p) => p.type === 'specials'))
this.getUserSpecials();
}).catch((error){
//error
});
},

Vuex promise reject returns undefined

I want the promise reject to return the error to my method but the response is empty inside my methods then() function, how can i get the error response to be returned to my method for further use or even inside the catch function.
My vuex action
//authAction
login({ commit }, payload) {
new Promise((resolve, reject) => {
user.login(payload.user.email, payload.user.password)
.then(response => {
const user = response.data.user;
// If there's user data in response
if (user) {
const payload = [user]
commit('AUTH_SUCCESS', payload, { root: true })
resolve(response)
} else {
reject({ message: "Sorry, cant login right now" })
}
})
.catch(error => {
console.log(error.response.status)
reject(error)
})
})
}
My method
// Login method
login() {
if (!this.checkLogin()) return;
this.$vs.loading();
const payload = {
checkbox_remember_me: this.checkbox_remember_me,
user: {
email: this.email,
password: this.password
}
};
this.$store
.dispatch("auth/login", payload)
.then(res => {
this.$vs.loading.close();
console.log(res);
})
.catch(error => {
this.$vs.loading.close();
this.$vs.notify({
title: "Error",
text: error.message,
});
});
}
What am i missing?
Thanks in advance!
My solution is to 1. dispatch an action whenever an error is thrown which updates state 2. watch state change in view and do something with it

Vuex update state by using store actions

I have two functions in my store, one that gets data by calling API and one that toggles change on cell "approved". Everything working fine, except that when I toggle this change it happens in database and I get the response that it is done but It doesn't update on UI.
I am confused, what should I do after toggling change to reflect change on UI, should I call my API from .then or should I call action method responsible for getting data from server.
export default {
state: {
drivers: {
allDrivers:[],
driversError:null
},
isLoading: false,
token: localStorage.getItem('token'),
driverApproved: null,
driverNotApproved: null
},
getters: {
driversAreLoading (state) {
return state.isLoading;
},
driverError (state) {
return state.drivers.driversError;
},
getAllDrivers(state){
return state.drivers.allDrivers
}
},
mutations: {
getAllDrivers (state) {
state.isLoading=true;
state.drivers.driversError=null;
},
allDriversAvailable(state,payload){
state.isLoading=false;
state.drivers.allDrivers=payload;
},
allDriversNotAvailable(state,payload){
state.isLoading=false;
state.drivers.driversError=payload;
},
toggleDriverApproval(state){
state.isLoading = true;
},
driverApprovalCompleted(state){
state.isLoading = false;
state.driverApproved = true;
},
driverApprovalError(state){
state.isLoading = false;
state.driverError = true;
}
},
actions: {
allDrivers (context) {
context.commit("getAllDrivers")
return new Promise((res,rej)=>{
http.get('/api/admin/getAllDrivers').then(
response=>{
if (response.data.success){
let data=response.data.data;
data=data.map(function (driver) {
return {
/* response */
};
});
context.commit("allDriversAvailable",data);
res();
}else {
context.commit("allDriversNotAvailable",response.data)
rej()
}
})
.catch(error=>{
context.commit("allDriversNotAvailable",error.data)
rej()
});
});
},
toggleDriverApproval (context, payload){
return new Promise((res, rej)=>{
http.post("/api/admin/toggleDriverApproval",{
driver_id: payload
})
.then( response => {
context.commit('driverApprovalCompleted');
res();
}).catch( error =>{
context.commit('driverApprovalError');
rej()
})
})
}
}
}
and here is the code on the view, I wrote the necessary code for better clarification of the problem
export default {
name: 'Drivers',
data: () => ({
data: [],
allDrivers: [],
driversErrors: []
}),
created() {
this.$store
.dispatch('allDrivers')
.then(() => {
this.data = this.$store.getters.getAllDrivers
})
.catch(() => {
this.errors = this.$store.getters.driverError
})
},
computed: {
isLoading() {
return this.$store.getters.driversAreLoading
}
},
methods: {
verify: function(row) {
console.log(row)
this.$store.dispatch('toggleDriverApproval', row.id).then(() => {
this.data = this.$store.getters.getAllDrivers
console.log('done dis')
})
},
},
}
if I understand your issue, you want the UI displaying your data to change to the updated data after making a post request.
If you are using Vuex you will want to commit a mutation, and use a getter display the data.
I am not sure how your post request is being handled on the server but if successful typically you would send a response back to your front end with the updated data, and commit a mutation with the updated data.
Example:
Make a Post request
toggleDriverApproval (context, payload){
return new Promise((res, rej)=>{
http.post("/api/admin/toggleDriverApproval",{
driver_id: payload
})
.then( response => {
context.commit('driverApprovalCompleted', response.data);
res();
}).catch( error =>{
context.commit('driverApprovalError', error.response.data);
rej()
})
})
}
If succesful commit the mutation
.then( response => {
context.commit('driverApprovalCompleted', response.data);
res();
})
response.data being your data you want to mutate the state with.
Mutation Example:
customMutation(state, data) {
state.driverApproval = data
}
Getter Example:
driver(state) {
return state.driverApproval
}
displaying the getter in a template
<template>
<div v-if="driver">{{driver}}</div>
</template>
<script>
import {mapGetters} from 'vuex'
export default {
name: Example,
computed: {
driver() {
return this.$store.getters.driver
},
// or use mapGetters
...mapGetters(['driver'])
}
}
</script>
more examples can be found at Vuex Docs

Nuxt.js issue where store state is updating before the url changes

I'm currently learning Nuxt.js and hope you can help me.
I have an error when navigating between pages there is a flash for a few milliseconds where my store state updates right before the page url finishes rendering so you see the next page content on the old template briefly and I can't work out why!
Here is the scenario. I'm viewing the /terms/ page and then I navigate to the homepage by clicking the logo. The homepage content renders under the pages/_slug/index.vue file for a brief moment until the page url renders.
I noticed it only occurs when the links are <nuxt-link to="/"> If I use traditional <a :href="/"></a> the issue doesn't occur.
I have a global page state in the Vuex store which changes from page to page and gets updated via the asyncData method.
Store: store/index.js
import Vuex from 'vuex';
import api from '~/api';
const store = () => {
return new Vuex.Store({
state: {
page: null,
},
actions: {
getHomepage({ commit }) {
return new Promise((resolve, reject) => {
api.getHomepage().then(response => {
commit('setPage', response);
resolve(response);
})
.catch(error => {
reject(error);
});
});
},
getPage({ commit }, slug) {
return new Promise((resolve, reject) => {
api.getPage(slug).then(response => {
commit('setPage', response);
resolve(response);
})
.catch(error => {
reject(error);
});
});
}
},
mutations: {
setPage(state, page) {
state.page = page;
}
}
})
}
export default store;
Homepage template: pages/index.vue
async asyncData({ store, error, payload }) {
if(payload) {
store.commit('setPage', payload.page);
} else {
return Promise.all([
store.dispatch('getHomepage')
]).catch(() => {
error({ message: 'Page not found' });
});
}
}
Other page template: pages/_slug/index.vue
async asyncData ({ store, params, error, payload }) {
if(payload) {
store.commit('setPage', payload.page);
} else {
return Promise.all([
store.dispatch('getPage', params.slug)
]).catch(() => {
error({ message: 'Page not found' });
});
}
}
I have a feeling it's because the page state is shared across all pages, and when I update the state from page to page it renders the update on the page I'm viewing because it's reactive and watches for changes.
How do I overcome this problem? Is it simply not possible to have 1 state called "page"?

Passing an error to a component

I have an AddComment.vue component which has a form, on submit it hits a laravel api endpoint where validation happens. If validation fails I want to show the errors in AddComment.vue. How can return the error.response object to AddComment.vue? Currently, I can see 'fired' in the console when I want to be logging the error. Where am I going wrong any help would be greatly appreciated
AddComponent.vue
methods: {
addComment() {
this.$store.dispatch('addComment', {
name: this.name,
email: this.email,
body: this.body
})
.then(response => {
this.$router.push({ name: 'home' })
console.log('fired')
})
.catch(error => {
console.log(error)
})
},
}
store.js
actions: {
addComment(context, comment) {
new Promise((resolve, reject) => {
axios.post('/comments', {
name: comment.name,
email: comment.email,
body: comment.body,
approved: false
})
.then(response => {
context.commit('addComment', response.data)
resolve(response)
})
.catch(error => {
reject(error)
})
});
},
}
The catch() block only gets called if the Laravel backend throws an error. So if you are returning a normal status code of 2xx then axios always calls the .then() part. In that case, you have to resolve the error message yourself.
Try something like this in your backend route (it will return an error):
return response()->toJson([
'message' => 'error message',
], 500);
And see if this responds with an actual error in you vuejs application.