Unspecified variables although I've used them - vue.js

I have a site that I initially want to create an interface for SignUp and login, I created a page for Login with all the data needed to be placed, but this error appeared to me how can I handle it?
C:\Users\Super\Desktop\tatbekat\my-app\src\pages\Auth\login.vue
60:8 error 'axios' is defined but never used no-unused-vars
81:13 error 'success' is defined but never used no-unused-vars
84:14 error 'error' is defined but never used no-unused-vars
This is the login page that contains the login form and a set of data that must be set in addition to a special login function.
login.vue:
<template>
<v-container>
<v-layout row>
<v-flex xs12 sm6 offset-sm3>
<v-card>
<v-alert color="error" :value="error" icon="close"> </v-alert>
<v-card-text>
<v-container>
<form #click="onLogin">
<v-layout row>
<v-flex xs12>
<v-text-field
name="email"
label="Email"
id="email"
v-model="loginUser.email"
type="text"
color="#43A047"
required
>
{{ email }}
</v-text-field>
</v-flex>
</v-layout>
<v-layout row>
<v-flex xs12>
<v-text-field
name="password"
label="Password"
id="password"
v-model="loginUser.password"
type="password"
color="#43A047"
required
>
{{ password }}
</v-text-field>
</v-flex>
</v-layout>
<v-layout row>
<v-flex xs12>
<v-btn class="green darken-1 color">
Sign In
</v-btn>
</v-flex>
</v-layout>
</form>
</v-container>
</v-card-text>
</v-card>
</v-flex>
</v-layout>
</v-container>
</template>
<script>
import { mapActions } from 'vuex'
import axios from "axios";
export default {
data() {
return {
loginUser: {
email: "",
password: "",
error: false
},
};
},
method: {
...mapActions([
'LOGIN'
]),
onSignIn(){
this.$store.dispatch('LOGIN',{
email:this.loginUser.email,
password:this.loginUser.password
})
.then(success=>{
this.$router.push("/")
})
.catch(error => {
this.error = true
})
}
},
};
</script>
<style scoped>
.color {
color: #fafafa;
}
</style>
And in this file, they wrote the necessary actions for the login and signup process.
user-store.js:
import axios from "axios";
export default {
state: {},
getters: {},
mutations: {},
actions: {
SIGNUP: (/*{ commit },*/ payload) => {
return new Promise((resolve, reject) => {
axios.post(`/signup` , payload)
.then(({/*data ,*/ status }) => {
if (status === 200){
resolve(true)
}
})
.catch(error =>{
reject(error)
})
});
},
LOGIN: (/*{ commit },*/ payload) => {
return new Promise((resolve, reject) => {
axios.post(`/signin` , payload)
.then(({/*data ,*/ status }) => {
if (status === 200){
resolve(true)
}
})
.catch(error =>{
reject(error)
})
});
},
},
};

All the errors are coming from login.vue file:.
axios: you have imported axios in login.vue but the actual axios calling is in the store file so the axios in login.vue is not used and you can delete the import.
success: in onSignIn method in login.vue you didn't use success in then call back so you can rewrite it like this:.
.then(() => {this.$router.push('/')}).
error: like the previous one you can rewrite catch block in login.vue like this:.
.catch(() => {this.error = true})

Related

Handling of user status already exists at login

I have a form to sign in and another form to sign up, and I have a store file, and when I enter user data, the data is stored in the local storage and VueX.
And all users are stored in the matrix "user".
And now I want to verify when I'm running a login.
If the user already exists, a message that "he already exists" should appear.
How can I solve the problem?
This is store file, in which a set of functions is written and in it there is a "user" array.
store.js:
import Vue from 'vue'
import Vuex from 'vuex'
const LOGIN = "LOGIN";
const LOGIN_SUCCESS = "LOGIN_SUCCESS";
const LOGOUT = "LOGOUT";
import image1 from '../assets/img/image4.jpg'
import image2 from '../assets/img/image2.jpg'
import image3 from '../assets/img/image3.jpg'
import image4 from '../assets/img/insta2.jpg'
Vue.use(Vuex)
export const store = new Vuex.Store({
state:{
isLoggedIn: !!localStorage.getItem('token'),
user:[
{name:'Hiba',
email:'Hiba69#gmail.com',
password:'123442321325'
}
]
},
mutations:{
createUser(state,payload){
state.user.push(payload)
}
},
},
getters:{
loadedUsers(state){
return state.user.sort((userA,userB)=>{
return userA.id >userB.id
})
},
isLoggedIn: state => {
return state.isLoggedIn
}
}
})
This is the signup file, through which you sign up to the site by entering the user's data.
signup.vue:
<template>
<div>
<v-container>
<v-layout row>
<v-flex xs12 sm6 offset-sm3>
<v-card>
<v-img
height="180px"
:src="
'https://cdn.awave.se/wp-content/uploads/sites/3/2019/02/case_greenfood_1new.jpg'
"
></v-img>
<v-card-text>
<v-container>
<form #click="onSignUp">
<v-layout row>
<v-flex xs12>
<v-text-field
name="id"
label="Id"
id="id"
v-model="id"
type="number"
color="#43A047"
required
>
{{ id }}
</v-text-field>
</v-flex>
</v-layout>
<v-layout row>
<v-flex xs12>
<v-text-field
name="name"
label="Name"
id="name"
v-model="name"
type="text"
color="#43A047"
required
>
{{ name }}
</v-text-field>
</v-flex>
</v-layout>
<v-layout row>
<v-flex xs12>
<v-text-field
name="email"
label="Email"
id="email"
v-model="email"
type="text"
color="#43A047"
required
>
{{ email }}
</v-text-field>
</v-flex>
</v-layout>
<v-layout row>
<v-flex xs12>
<v-text-field
name="password"
label="Password"
id="password"
v-model="password"
type="password"
color="#43A047"
required
>
{{ password }}
</v-text-field>
</v-flex>
</v-layout>
<v-layout row>
<v-flex xs12>
<v-btn class="green darken-1 color">
Sign up
</v-btn>
</v-flex>
</v-layout>
</form>
</v-container>
</v-card-text>
</v-card>
</v-flex>
</v-layout>
</v-container>
</div>
</template>
<script>
export default {
data() {
return {
id: "",
name: "",
email: "",
password: "",
};
},
computed: {
formIsValid() {
return (
this.id !== "" &&
this.name !== "" &&
this.email !== "" &&
this.password !== ""
);
},
},
watch: {
name(newName) {
localStorage.name = newName;
},
},
methods: {
onSignUp() {
if (!this.formIsValid) {
return;
}
const signup = {
name: this.name,
email: this.email,
password: this.password,
};
console.log(signup);
this.$store.commit("createUser", signup);
const stringifiedData = JSON.stringify(signup);
// console.log("S: ", stringifiedData);
localStorage.setItem("signup", stringifiedData);
console.log("We got : ", JSON.parse(localStorage.getItem("signup")));
},
},
};
</script>
<style scoped>
.color {
color: #fafafa;
}
</style>
This is the login file, through which you log in to the site by entering the user's data.
signin.vue:
<template>
<v-container>
<v-layout row>
<v-flex xs12 sm6 offset-sm3>
<v-card>
<v-card-text>
<v-container>
<form #click="onSignIn">
<v-layout row>
<v-flex xs12>
<v-text-field
name="email"
label="Email"
id="email"
v-model="email"
type="text"
color="#43A047"
required
>
{{ email }}
</v-text-field>
</v-flex>
</v-layout>
<v-layout row>
<v-flex xs12>
<v-text-field
name="password"
label="Password"
id="password"
v-model="password"
type="password"
color="#43A047"
required
>
{{ password }}
</v-text-field>
</v-flex>
</v-layout>
<v-layout row>
<v-flex xs12>
<v-btn class="green darken-1 color">
Sign In
</v-btn>
</v-flex>
</v-layout>
</form>
</v-container>
</v-card-text>
</v-card>
</v-flex>
</v-layout>
</v-container>
</template>
<script>
export default {
data() {
return {
email: "",
password: "",
};
},
methods: {
onSignIn() {
const signin = {
email: this.email,
password: this.password,
};
console.log(signin);
const stringifiedData = JSON.stringify(signin);
localStorage.setItem("signin", stringifiedData);
console.log("We got : ", JSON.parse(localStorage.getItem("signin")));
},
}
};
</script>
<style scoped>
.color {
color: #fafafa;
}
</style>
You should check if there is an user, when you created the app.
At main.js, you could use something like that;
new Vue({
el: '#app',
router,
store,
render: h => h(App),
created() {
if (localStorage.getItem("user")) {
store.dispatch("autoSignIn", localStorage.getItem("user"));
}
}
And in your vuex store, create autoSignIn method,
autoSignIn({ commit }, payload) {
commit("setLoading", true);
var token = JSON.parse(payload);
var decoded = jwt.verify(token, process.env.VUE_APP_TOKEN);
var loggedUser = {
id: decoded.id,
email: decoded.email
};
commit("setUser", loggedUser);
commit("setLoading", false);
},
And in your signup or login page, if your user state is not null, you can redirect them to the page you want to..
It is better practice to redirect user before rendering the page, so you could use router to check;
{
path: "/login",
beforeEnter: (to, from, next) => {
if (!store.getters.user) {
{
next();
}
} else {
next("/user_secret_page");
}
}
},

Vue Passing Data from component to another component

I am making a "create account" flow for user and I am not able to pass data from one component to another. The first component has radio buttons with options of "tenant", "landlord", "contractor". Once the user selects "tenant", then the data should pass to the next step where they fill out a form with name and all that good stuff.. once they submit, it should all go together to the back end.
acc-for.vue with radio buttons component below.
<template>
<div>
<v-app
style="background-image: url('https://blog.modsy.com/wp-content/uploads/2019/06/D2_Full.jpg')"
>
<v-container class="pa-12">
<v-row>
<v-card class="pa-16">
<v-card-title>
Are you a?
</v-card-title>
<v-radio-group v-model="selectedValue" #change="selectedAcc">
<v-radio
v-for="account in accountType"
:key="account.name"
:value="account.name"
:label="account.name"
></v-radio>
</v-radio-group>
<v-row>
<v-btn rounded color="black" class="white--text" href="/login"
>Back</v-btn
>
<v-btn
rounded
color="black"
class="white--text"
#click="selected(accountSelected)"
>Next</v-btn
>
<!-- href="/create-acc" -->
</v-row>
</v-card>
</v-row>
</v-container>
</v-app>
</div>
</template>
<script>
import { mapMutations } from "vuex";
export default {
data() {
return {
selectedValue: false,
};
},
computed: {
accountType() {
return this.$store.state.accountType;
},
selected() {
return this.$store.state.selectedAccType;
},
},
methods: {
...mapMutations(["SELECTED_ACCOUNT_TYPE"]),
selectedAcc(e) {
this.$emit("selected-accountType", e);
},
},
};
</script>
<style></style>
createAccount.vue this component has the form for the fName and lName and all that good stuff..
<template>
<div>
<v-app
style="background-image: url('https://blog.modsy.com/wp-content/uploads/2019/06/D2_Full.jpg')"
>
<v-container class="pa-12">
<v-row>
<v-card class="pa-16">
<v-card-title>
{{ selectedTypeUser }}
</v-card-title>
<v-form>
<v-text-field
class="pa-4"
type="text"
v-model="newUser_fName"
label="First Name"
/>
<v-text-field
class="pa-4"
type="text"
v-model="newUser_lName"
label="Last Name"
/>
<v-text-field
class="pa-4"
type="text"
v-model="newUser_email"
label="Email"
/>
<v-text-field
class="pa-4"
type="text"
v-model="newUser_password"
label="Password"
/>
<v-row>
<v-btn rounded color="black" class="white--text" href="/acc-for"
>Back</v-btn
>
<v-btn
#click="registerUser"
rounded
color="black"
class="white--text"
>Next</v-btn
>
</v-row>
</v-form>
</v-card>
</v-row>
</v-container>
</v-app>
</div>
</template>
<script>
import { mapMutations } from "vuex";
import axios from "axios";
export default {
data() {
return {
newUser_fName: "",
newUser_lName: "",
newUser_email: "",
newUser_password: "",
};
},
methods: {
...mapMutations(["ADD_USER"]),
registerUser() {
let config = {
headers: {
"Content-Type": "application/json",
},
};
axios
.post(
"http://localhost:7876/createUser",
{
fName: this.newUser_fName,
lName: this.newUser_lName,
email: this.newUser_email,
password: this.newUser_email,
},
config
)
.then((response) => {
console.log(response.statusText);
})
.catch((e) => {
console.log("Error: ", e.response.data);
});
},
},
};
</script>
store.js (state) is below
// import vue from "vue";
import vuex from "vuex";
import axios from "axios";
import Vue from "vue";
Vue.use(vuex, axios);
export default new vuex.Store({
state: {
users: [],
accountType: [
{ name: "Tenant" },
{ name: "Landlord" },
{ name: "Contractor" }
],
selectedAccType: [],
},
mutations: {
ADD_USER: (state, payload) => {
state.users.push(payload.user);
},
SELECTED_ACCOUNT_TYPE: (state, payload) => {
state.selectedAccType.push(payload)
}
},
actions: {
addUser: ({ commit }, payload) => {
commit("ADD_USER", payload);
},
selectAcc: ({ commit }, payload) => {
commit("SELECTED_ACCOUNT_TYPE", payload)
}
},
// getters: {
// addAccountType(state, e) {
// state.accountType.push(e)
// },
// },
});
I see this on the button:
<v-btn rounded
color="black"
class="white--text"
#click="selected(accountSelected)"
>Next</v-btn
>
But I'm not finding a method with that name in your attached code. Double check that your names are all matched up and that you are calling the correct function on the click event.

Vue, error [vuex] do not mutate vuex store state outside mutation handlers

Here is original code. Very simple, sign in form. We have Email field, password. It takes this parameters and on clicking submit button it checks the user and writes his user.uid into Vuex. But I'm getting error which is listed above in title. I did research and it looks like it's a common issue in Vuex, due to those fields at some point updating Vuex store 'on a fly' which is false in my case, cause it only updates Vuex store when you press a submit button. Anyhow decided corrected to be look like this and still have no luck
original code
<template>
<div class="form__inner">
<div class="overlay" #click="$store.commit('logReg/logIn')"></div>
<v-container
fill-height
fluid>
<v-row
align="center"
justify="center">
<v-col cols="2">
<v-card>
<v-card-title>
Log in
</v-card-title>
<v-card-text>
<v-text-field placeholder="Email"
v-model="logIn"/>
<v-text-field placeholder="Password"
v-model="password"/>
</v-card-text>
<v-card-actions>
<v-btn color="success"
class="mx-auto"
#click="signIn">Log me in</v-btn>
</v-card-actions>
</v-card>
</v-col>
</v-row>
</v-container>
</div>
</template>
<script>
export default {
data(){
return {
logIn: '',
password: ''
}
},
methods: {
async signIn(){
let res = await this.$fireAuth.signInWithEmailAndPassword(this.logIn, this.password);
this.$store.commit('userState', res);
}
}
}
</script>
my vuex
export const state = () => ({
user: null
})
export const mutations = {
userState(state, authUser){
state.user = authUser;
}
}
my try to fix issue which still had no luck, gives same error
<template>
<div class="form__inner">
<div class="overlay" #click="$store.commit('logReg/logIn')"></div>
<v-container
fill-height
fluid>
<v-row
align="center"
justify="center">
<v-col cols="2">
<v-card>
<v-card-title>
Log in
</v-card-title>
<v-card-text>
<v-text-field placeholder="Email"
v-model="logIn"/>
<v-text-field placeholder="Password"
v-model="password"/>
</v-card-text>
<v-card-actions>
<v-btn color="success"
class="mx-auto"
#click="signIn">Log me in</v-btn>
</v-card-actions>
</v-card>
</v-col>
</v-row>
</v-container>
</div>
</template>
<script>
export default {
data(){
return {
logIn: '',
password: ''
}
},
computed: {
logg: {
get(){
return this.logIn;
},
set(val){
this.logIn = val;
}
},
pass: {
get(){
return this.password;
},
set(val){
this.password = val;
}
}
},
methods: {
async signIn(){
let res = await this.$fireAuth.signInWithEmailAndPassword(this.logg, this.pass);
this.$store.commit('userState', res);
}
}
}
</script>
You have to use mutations like this:
<script>
import {mapMutations} from 'vuex';
export default {
data(){
return {
logIn: '',
password: ''
}
},
methods: {
...mapMutations({
userState: 'userState'
}),
async signIn(){
let res = await this.$fireAuth.signInWithEmailAndPassword(this.logIn,this.password);
this.userState(res);
}
}
}
</script>

Call to database after successful login is not being made

I'm having difficulty in getting an axios call to my database being initiated after a user has logged into my SPA.
A route (gaplist/3) brings the user to a page (gaplist.vue) which
detects if the user is logged in or not.
If not logged in, a login form is presented.
Once the entered username/password combo is accepted, the user is "pushed" to the same page (gaplist/3)
Here, the logged in status is detected and - this is where it all falls down - a call to the database would return a bunch of records associated with the user and the parameter "3".
Unfortunately, the last step doesn't fully happen. The logged in status is detected, but the database call is not made. Only if I refresh the page is the call made and the results presented.
What concept am I not grasping here?
Thanks, Tom.
My code is as follows:
GapList.vue (route: gaplist/3)
<template>
<v-content>
<v-container fluid fill-height>
<v-layout justify-center>
<v-flex xs12 sm6>
<h1>Production and sale of produce</h1>
<v-card flat>
<div v-if="isIn">
<p v-for="(card, id) in cards">{{card.product}}</p>
<logout-button></logout-button>
</div>
<div v-else>
<gap-login :gapid=gapid></gap-login>
</div>
</v-card>
</v-flex>
</v-layout>
</v-container>
</v-content>
</template>
<script>
import GapLogin from '../components/gap/GapLogin';
import LogoutButton from '../components/gap/LogoutButton'
export default {
name: 'GapList',
components: {
GapLogin,
LogoutButton
},
data () {
return {
gapid: this.$route.params.id,
cards: [],
lang: this.$i18n.locale,
bNoRecords: false,
}
},
created(){
this.loadCrops(this.gapid,this.lang)
},
computed: {
isIn : function(){ return this.$store.getters.isLoggedIn},
},
methods: {
loadCrops(gapid,lang){
var vm = this;
if (this.isIn){
axios.get('/gapcroplist/' + gapid)
.then(function (resp) {
vm.cards = resp.data;
})
.catch(function (resp) {
vm.bNoRecords = true;
});
}
},
}
}
</script>
GapLogin.vue
<template>
<div class="formdiv">
<v-layout justify-center>
<h3>Login</h3>
<v-card flat>
<v-alert
v-if="loginError"
:value="true"
type="error"
transition="scale-transition"
dismissible
>
You didn't enter correct information
</v-alert>
<v-form class="login" #submit.prevent="login">
<v-text-field
v-model="form.email"
type="email"
label="Email"
required
autofocus
></v-text-field>
<v-text-field
v-model="form.password"
type="password"
label="Password"
required
></v-text-field>
<v-btn
type="submit"
>Login in </v-btn>
</v-form>
</v-card>
</v-layout>
</div>
</template>
<script>
export default {
name: "GapLogin",
props: ['gapid'],
data() {
return {
form: {
email: null,
password: null
},
loginError:false
}
},
methods: {
login: function () {
this.loginError = false
this.$store.dispatch('login', this.form)
.then(() =>
{this.$router.push({path: '/gaplist/' + this.gapid})
})
.catch(err => {
this.loginError = true
}
)
},
}
}
</script>
Updated answer:
created hook will not be called again. Using updated will result in an error as well, as you would trigger another update and have an endless loop.
Instead of pushing to same route I would suggest that you emit a completed event:
In your login method in then instead of $router.push:
this.$emit('completed')
And register the event on the gap-login-component:
<gap-login #completed="completed" :gapid=gapid></gap-login>
And add that method to the GapList.vue-file:
completed () {
this.loadCrops(this.gapid, this.lang)
}
You are using axios in a global context, but it doesn't exists, it seems.
Try using this.$axios:
this.$axios.get('/gapcroplist/' + gapid)

How get the Vue instance from vuetify with vue-axios

I create a project with Vuetify and vue-axios, and create a simple login component, but I have problem to get the Vue instance
this is my login component:
<template>
<v-app id="inspire">
<v-content>
<v-container fluid fill-height>
<v-layout align-center justify-center>
<v-flex xs12 sm8 md4>
<v-card class="elevation-12">
<v-toolbar dark color="primary">
...
</v-toolbar>
<v-card-text>
...
</v-card-text>
<v-card-actions>
<v-spacer></v-spacer>
<v-btn color="primary" #click='logar()'>Entrar</v-btn>
</v-card-actions>
</v-card>
</v-flex>
</v-layout>
</v-container>
</v-content>
</v-app>
</template>
<script>
export default {
name: 'Login',
data: () => ({
drawer: null,
checkbox: false,
username: 'cartorio#teste.com.br',
password: '1234',
}),
props: {
source: String,
},
methods: {
logar() {
var myVue = this.$vuetify;
this.axios.post('http://localhost:8585/login', {
email: this.username,
senha: this.password,
},
{
withCredentials: false,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
},
).then((response) => {
//HERE I NEED TO USE myVue
window.AUT = response.headers.authorization;
}).catch((error) => {
console.log(error);
});
},
},
};
</script>
so, inside axios promisse, then I need to use my var myVue, so why always get undefined?
tks