How to manually trigger routing on nuxt.js? - vue.js

I want to navigate manually to home page after login in callback.
methods: {
async userLogin() {
var session_url = "/api/v1/authenticate";
axios
.post(session_url, this.login, {})
.then(function (response) {
console.log("Authenticated", response.data.access_token);
window.localStorage.setItem("token", response.data.access_token);
// Manually trigger route here.
})
.catch(function (error) {
console.log("Error on Authentication", error);
});
},
},

To manually trigger route, you can use below code, where / is home route.
Note: No need to import anything as $router is globally available.
this.$router.push("/" )

Related

why i can not update data using vuex module?

here is my component
methods:{
...mapActions(['udpateUsers']),
Update(userID){
let formData = new FormData();
formData.append('new_name',this.editUser.new_name);
formData.append('_method', 'PUT');
let config = {
headers:{
'Content-Type':'multipart/form-data',
}
}
this.udpateUsers(userID,formData,config);
}
when i click update button the formData can not be sent to the server but when i console it the FormData is has all the fields
here is my modules
mutations:{
ADD_USER: (state,response)=>{
state.Users = response;
},
UPDATE_USERS: (state,response)=>{
state.Users = response;
}
},
actions:{
udpateUsers: ({commit},userID,formData,config)=>{
http.put("/admin/update/"+userID,formData,config)
.then((response)=>{
commit("UPDATE_USERS",formData);
console.log(response);
})
.catch((error)=>{
console.log(error.response);
})
}
}
export default auth
i think the error will be my commit mutation
You can't pass multiple parameters as payload to Vuex Actions. You'll need to wrap it all up in an object and pass it as a single param.
udpateUsers: ({commit}, { userID, formData, config }) => {
// send to backend
}
this.udpateUsers({ userID, formData, config });
EDIT: From comments, it seems that you're using PUT method instead of POST in your VueX implementation, which is why your backend wasnt getting the data.

sending back api data to vue in express returns empty object

I'm trying to send some data back from my express app using the following in my app.js this data comes from a 3rd party api and I want to send it back to my front end application. I am able to see the content in my express api but it doesn't seem to deliver a result to my front end?? anyone have any ideas as to why I'm getting log below in the console.
I suspect it has to do with some async or timeout issue with the express app but I haven't been able to fix the issue myself.
function getFish(){
axios.get('https://www.fishwatch.gov/api/species')
.then(function (response) {
console.log(response)
return response
})
.catch(function (error) {
console.log(error);
})
}
app.get('/getFish', async(req,res) =>{
let fish = await getFish()
res.json({fishes: fish})
})
when I try to log the data in my app, I only get an empty object
{}
here is my vue code to log the value's returned by my express api.
created:function(){
this.fetchFish()
},
methods: {
fetchFish(){
fetch('http://localhost:3000/getFish')
.then((response) => {
return response.json();
})
.then((data) => {
console.log(data);
});
}
}
You need to return the axios promise in your server's getFish function or the /getFish route won't be awaiting anything:
function getFish(){
// New `return` statement
return axios.get('https://www.fishwatch.gov/api/species')
.then(function (response) {
console.log(response)
return response
})
.catch(function (error) {
console.log(error);
})
}

better nuxt vuex workflow?

So...
I am developing a app with Nuxt
I have this following structure for my front-end but I don't know if this is the right way to do it,
basically I am dispatching VueX actions
component.vue
await this.$store.dispatch('auth/login', {email, password})
In auth/login vuex module I am doing this:
store/auth.js
async login({commit}, {email, password}){
try {
let user = await this.$repositories.auth.login({email, password})
await commit('SET_AUTH_INSTANCE', user)
await commit('SET_AUTH_TOKEN', user.token)
} catch (error) {
}
},
What am I actually asking...
Should I change the business logic? Should I call the repository API's in vue components and dispatching actions only with the payload so I can commit them ?
for example:
component.vue
let user = await this.$repositories.auth.login({email, password})
await this.$store.dispatch('auth/login', user)
store/auth.js
async login({commit}, user){
try {
await commit('SET_AUTH_INSTANCE', user)
await commit('SET_AUTH_TOKEN', user.token)
} catch (error) {
}
},

Vue returning from a promise

I am trying to return some value from this dispatch
this.$store.dispatch('setValue', this.Value)
.then(response => {
console.log(response)
});
In my vuex action I have
.catch(error => {
if (error.response.status === 412) {
return "some message"
}
});
How can I pass the error back to the .vue file where the vuex dispatch is made?
I think the correct way of doing this is to have a status property in your store.
Your status object would consist out of error, success, loading.
So if your action throw exception you can handle it like this:
catch (error) {
commit("error", `Some Message`);
}
Your error mutation would look like this:
error(state, payload) {
state.status.success = false;
state.status.loading = false;
state.status.error = payload || false;
}
Your template would just listen on the store.state.status
<div v-if="store.state.status.error">{{store.state.status.error}}</div>
I might be wrong but in my personal opinion I feel it is wrong to use actions to return stuff. Your using the store so might as well leverage it best you can.
Other extra benefits is, you can indicate to your .vue file if api is loading or when something is successful.
What I ended up doing was pretty simple. I chained the catch to my dispatch:
this.$store.dispatch('setValue', this.Value)
.then(response => {
console.log(response)
})
.catch(error => {
if (error.response.status === 412) {
return "some message"
}
});
Then I returned the Axios call from the action:
return axios({
method: 'post',
url: `/mypath,
data: mydata,
json: true,
})
This means I could deal with the returned data/errors locally where I wanted to trigger an action.
Store:
.catch(error => {
if (error.response.status === 412) {
throw error
}
});
Vue element with async method:
try{
let response = await this.$store.dispatch('setValue', this.Value)
} catch(error) {
console.log(error)
});

redirect after axios response with vue

Ok, so i have the following method. Basically I am calling an API backend, posting username and password, and if those pass, in the response, the server sends me a 200 status. What I want to do, is in the response, after I get the status, run an if/else, so if the status is 200, redirect, else display an error message. every time i try to use 'this.$router.push('/any route here')',
I get an error: 'homepage.vue?3ec6:72 Uncaught (in promise) TypeError: Cannot read property '$router' of undefined'.
But if i use the same route at the top of the method, outside the axios call, it works fine.
So what am i missing here?
hero_login: function(event){
event.preventDefault();
axios.post('API call here',
{
service:'client',
user: this.user_email,
password: this.user_password,
json:true
})
.then(function(response){
const status =
JSON.parse(response.data.response.status);
console.log(status);
})
}
You have to define this outside axios methods because this inside axios refers to the axios object, not the vue component:
hero_login: function(event) {
let self = this;
event.preventDefault();
axios.post('API call here',
{
service:'client',
user: this.user_email,
password: this.user_password,
json:true
})
.then(function(response){
const status =
JSON.parse(response.data.response.status);
//redirect logic
if (status == '200') {
self.$router.push('/any route here');
}
})
}
}
Use route name
this.$router.push({name: 'home'});
this.$router.replace({name: 'home'});
Use route URL
this.$router.push('/home');
this.$router.replace('/home');
Such as Vue Router Documentation
please use this.$router.push('/home')
You can use easily redirect it by using,
.then(data => {
'this.$router.replace({ name: "home" });
});
OR,
.then(data => {
'this.$router.push({ name: "home" });
});