Vue2 populate inputs in edit view - vuejs2

I´m trying to create a simple CRUD in vue2 and works perfectly, but when i enter in edit view i need to fill form inputs based on Firebase data.
View
<v-text-field prepend-icon="person" v-model="user" name="user" label="User" type="text" required></v-text-field>
<v-text-field prepend-icon="mail" v-model="email" name="email" label="Email" type="email"></v-text-field>
JS
export default {
data: function () {
return {
user: '',
email: '',
drawer: null
}
var edit = ref.child(this.$route.params.id)
edit.on('value', function (snapshot) {
this.user = snapshot.val().name
this.email = snapshot.val().email
})
snapshot.val().name
Return name properly but when i try to assign this value to this.user does not work. Console does not return any error.
¿Anybody has a idea whats is the correct way?

export default {
data: function () {
return {
user: '',
email: '',
drawer: null
}
var edit = ref.child(this.$route.params.id)
var self = this;
edit.on('value', function (snapshot) {
self.user = snapshot.val().name
self.email = snapshot.val().email
})
It might be a scope issue. Try the code above to maintain the scope let’s see if that helps.

var edit = ref.child(this.$route.params.id)
edit.on('value', snapshot => this.user = snapshot.val().name)
edit.on('value', snapshot => this.email = snapshot.val().email)
This works, but exist a form to 'code' better?

Related

How to insert data from other tables in a third table in frontend project with vue

I have 4 tables, one for users, one for students, one for family of students, and the other one for the people that make registrations called "Auxiliar" in the code. I need to create the relation between familiar and students into a third table. There, i'd put through an input the students's ID, familiar's ID and the auxiliar's ID because she/he is the person with the authorization or token to make the registration. In the backend everything goes perfect but I have mistakes with the code in frontend. I got the error 500. Here's the code:
this is part where is the form where I send the input
enter code here
<form v-on:submit.prevent="processEstudianteFamiliar">
<label>Ingrese el Id del estudiante</label>
<input type="number" v-model="asignacion.estudiante"/>
<label>Ingrese el Id del familiar</label>
<input type="number" v-model="asignacion.familiar"/>
<label>Ingrese el Id del auxiliar</label>
<input type="number" v-model="asignacion.registra"/>
<button type="submit">Asignar</button>
</form>
Then this is the script
import axios from 'axios';
export default {
name: "EstudianteFamiliar",
data: function ()
{
return {
asignacion:{
estudiante: "",
familiar: "",
registra: ""
},
loaded: false,
}
},
methods:{
verifyToken : async function() {
return axios.post("http://127.0.0.1:8000/refresh/",
{refresh: localStorage.getItem("token_refresh")},
{headers:{}}
)
.then((result) => {
console.log("New access token");
localStorage.setItem("token_access", result.data.access);
})
.catch((error) => {
this.$emit("logOut");
})
},
processAsignarFamiliar: async function() {
if (localStorage.getItem("token_access") === null ||
localStorage.getItem("token_refresh") === null){
this.$emit('logOut');
return;
}
await this.verifyToken();
let token = localStorage.getItem("token_access");
console.log(this.asignacion,2)
console.log(token)
axios.post(
"http://127.0.0.1:8000/estudianteFamiliar/",
this.asignacion,
{headers: {'Authorization': `Bearer ${token}`} }
)
.then((result)=>{
let dataEstudianteFamiliar={
token_access: result.data.access,
token_refresh: result.data.refresh
}
console.log(result.data)
console.log(this.asignacion),
this.$emit('completedEstudianteFamiliar', dataEstudianteFamiliar);
})
.catch((error)=>{
console.log(error);
alert("Error: Falló la asignación del familiar del estudiante");
});
},
created: async function () {
this.processEstudianteFamiliar();
}
}
}
I'm doing something wrong in the frontend because when i test in postman the backend runs ok and create the relation in the database. I haven't found out what it is. The error send me to this in the backend and I guess i'm making the relation wrong in the code.
token = request.META.get('HTTP_AUTHORIZATION')[7:]
auxValido = validateAuxiliar(token, request.data['asignacion']['registra'])
the key error is the ['asignacion']
Thank you so much I'd apreciate your helph.

Vue 3: Field is not updating value

I have a field defined as follows:
<Field
class="form-control form-control-solid"
:value="tradeSizeFactor"
name="tradeSizeFactor"
:v-model="tradeSizeFactor"
/>
In my setup I watch if the value of property changed and if so I get the new value for for example the tradeSizeFactor:
setup(props)
{
const copyAccountId = ref(props.copyAccountId);
const copyAccountName = ref(props.copyAccountName);
let tradeSizeFactor = ref(0);
watchEffect(() => {
console.log(`watch Effect id: ${props.copyAccountId}`);
console.log(`watch Effect name: ${props.copyAccountName}`);
copyAccountId.value = props.copyAccountId;
if (props.copyAccountId !== 0) {
getSettings(props.copyAccountId);
}
});
async function getSettings(copyAccountId) {
store
.dispatch(Actions.GET_COPYACCOUNTSETTINGS, copyAccountId)
.then((data) => {
console.log(
`data: ${JSON.stringify(data.data.settings.tradeSizeFactor)}`
);
Object.assign(copyAccountSettings.value, data.data.settings);
tradeSizeFactor = data.data.settings.tradeSizeFactor;
});
}
return {
tradeSizeFactor,
};
}
Whatever I try however, the value of tradeSizeFactor is not updating in the Field. It keeps showing 0...
In the following line, you're incorrectly overwriting the ref with a literal:
tradeSizeFactor = data.data.settings.tradeSizeFactor;
^^^^^^^^^^^^^^^
tradeSizeFactor is a ref, so the value must be changed via its value property:
tradeSizeFactor.value = data.data.settings.tradeSizeFactor;
👆

BootstrapVue: Check database if username already exists: Optimal way to use debounce?

Can I get a second set of eyes on using a <b-form-input> with debounce prop?
Use case: I am making an expensive API call to check if a username already exist in a database:
<b-form-input
id="username_input"
v-model="formValues.username"
type="text"
debounce="500"
#input="usernameCheck"
></b-form-input>
and here's the input handler usernameCheck:
async usernameCheck() {
const username = this.formValues.username
if (username.length >= 3 && username.length <= 15) {
const ref = this.$fire.firestore.doc(`usernames/${username}`)
const { exists } = await ref.get() // here I'm checking if document exists already
this.usernameAvailable = !exists
} else {
...
}
Is this a good approach?
Or should I be using a watcher?
I think there is a better way to approach this. First, the key point I discovered is that there is a difference between using #input and #update as mentioned here:
The input event is emitted on user update. You have to use the update event which is triggered to update the v-model to get your expected result.
So, I have now updated my code as follows (with some additional validation UX messaging):
<b-form-input
id="username_input"
v-model="formValues.username"
type="text"
debounce="500"
:state="usernameValid"
trim
#update="usernameCheck"
></b-form-input>
valid: {{ state }}
<p v-show="formValues.username != '' && !usernameValid">
Username must be between 3 and 15 characters
</p>
<p v-show="usernameAvailable && usernameValid">Username is available!</p>
import { BFormInput } from 'bootstrap-vue'
export default {
components: {
BFormInput
},
data() {
return {
formValues: {
username: ''
},
usernameAvailable: false,
state: null,
}
},
computed: {
usernameValid() {
return (
this.formValues.username.length >= 3 &&
this.formValues.username.length <= 15
)
}
},
methods: {
async usernameCheck() {
const username = this.formValues.username
if (this.usernameValid) {
const ref = this.$fire.firestore.doc(`usernames/${username}`)
const { exists } = await ref.get() // checks if doc exists in firebase db
this.usernameAvailable = !exists
this.state = true // input now in valid state
} else {
console.log('not a valid username')
this.state = false
}
So this works for me, but I have not done a full test. I do see that the network polling is reduced due to debounce, too.
I'd be curious if anyone has any ways I can improve this (if needed!). Thanks!

How to retrieve data when component is loaded

I've got a list of projects, and I want to display the name of the clicked project in a modal on the next page, when I click on one of them, it loads without problem and displays the association name in my modal.
But the problem comes when I reload this project page, it throws an error "Cannot read property 'asso_id' of undefined""
I get the project by it's id with a getter to retrieve the asso_id in the project object, then use this asso_id with my association by id getter to get the related association.
I think it's because my component doesn't retrieve the AssociationTitle soon enough.
Here is my code
computed: {
"getProjectById",
"getAssociationById"
]),
project() {
const projectId = this.$route.params.id;
return this.getProjectById(projectId);
},
associationTitle() {
const project = this.project;
const association = this.getAssociationById(project.asso_id);
return association.title;
}
}
getters: {
getProjects: state => {
return state.projects = [...ProjectData.ProjectData];
},
getProjectById: state => id => {
return state.projects.find(project => project._id === id);
},
getAssociations: state => {
return state.associations = [...AssociationData.AssociationData];
},
getAssociationById: state => id => {
state.associations = [...AssociationData.AssociationData];
return state.associations.find(association => association._id === id);
}
}
<v-card-title class="headline grey lighten-2" primary-title> {{ associationTitle }} </v-card-title>
I think you're guessing it right. You can just check if you have the project e.g.
associationTitle() {
const project = this.project;
const title = project ? this.getAssociationById(project.asso_id).title : '';
// or typeof project !== 'undefined' or something similar
return title;
}

How to pass an array values from one function to another function in vuejs?

I am trying to get the array values from
"validateBeforeSubmit" function to "saveForm" function. But I am
getting values of "undefined" in "arrlength". Please help me to solve.
This my code in vue.js
export default {
name: '',
data() {
return {}
},
ready: function() {
this.validateBeforeSubmit()
this.saveForm();
},
methods: {
validateBeforeSubmit() {
var fieldsVal = new Array();
var firstName = document.getElementById('firstName').value
var lastName = document.getElementById('lastName').value
var designation = document.getElementById('designation').value
if (firstName != "" && lastName != "" && designation != "") {
fieldsVal.push(firstName);
fieldsVal.push(lastName);
fieldsVal.push(designation);
return fieldsVal;
} else {
fieldsVal.length = 0;
return fieldsVal;
}
return fieldsVal;
},
saveForm() {
var fieldsValArray = this.validateBeforeSubmit();
var arrLength = fieldsValArray.length;
}
}
}
I can see multiple issues in your code:
1) Don't apply jQuery-like approach for getting input values. Use v-model instead. This will simplify your code
<template>
<input v-model="form.firstName" type="text"/>
</template>
<script>
export default {
data: {
form: {
firstName: '',
}
},
methods: {
validateBeforeSubmit() {
// take `firstName` directly from `data` not need for `getElementById`
const firstName = this.form.firstName;
}
},
}
</script>
2) Remove validateBeforeSubmit and saveForm from ready. Ready hook is obsolete in vue#2. And also it makes no sense. It's better to call it on form #submit.
3) It's better to create array using [] syntax instead of new Array()
Why never use new Array in Javascript
4) Always provide name for your component for easier debug
export default {
name: 'ValidationForm',
}
5) I don't know where was an issue but it works. Check this link below. I have updated your code. Try to submit form and check the console:
https://codesandbox.io/s/w6jl619qr5?expanddevtools=1&module=%2Fsrc%2Fcomponents%2FForm.vue