How to set input value from method? - javascript

I create check-in system (Laravel + Vuetify), so i would like to ask: how to get userID from an object (API) en put them into input?
<template>
<v-text-field
v-model="debugItem.extra1_int"
:counter="250"
label="extra1_int"
hint="userID"
type="number"
clearable>
</v-text-field>
</template>
<script>
export default {
data() {
return {
debugItem: {}, /* store new debugItem */
user: '',
}
},
mounted() {
this.getUser();
this.debugItem.extra1_int = ***how to put here userID?***;
},
methods: {
getUser() {
axios.get('/user')
.then(response => (this.user = response.data))
.catch(error => console.log(error));
},
addDebugItem() { /* store new debugItem */
this.axios
.post('/api/debugs', this.debugItem)
.then(response => (
this.$router.push({name: 'indexDebugs'})
))
.catch(err => console.log(err))
.finally(() => this.loading = false)
}
}
}
</script>
Method getUser() http://127.0.0.1:8000/user return json-object of logged user:
{
"id": 119,
"name": "Johan",
"email": "Johan#mail.com",
"email_verified_at": null,
"is_active": 1,
"created_at": "2022-05-09T14:24:48.000000Z",
"updated_at": "2022-05-09T14:24:48.000000Z"
}
Thanks.

<template>
<v-text-field
v-model="debugItem.userId"
:counter="250"
label="extra1_int"
hint="userID"
type="number"
clearable>
</v-text-field>
</template>
<script>
export default {
data() {
return {
debugItem: {userId: null}, /* store new debugItem */
user: '',
}
},
mounted() {
this.getUser();
this.debugItem.userId = this.user.id
},
methods: {
getUser() {
axios.get('/user')
.then(response => (this.user = response.data))
.catch(error => console.log(error));
},
addDebugItem() { /* store new debugItem */
this.axios
.post('/api/debugs', this.debugItem)
.then(response => (
this.$router.push({name: 'indexDebugs'})
))
.catch(err => console.log(err))
.finally(() => this.loading = false)
}
}
}
</script>

My suggestion, Instead of assigning value to this.debugItem.extra1_int in mounted() lifecycle hook. You can assign it in getUser() on success of axios call.
data() {
return {
debugItem: {},
user: '',
}
},
mounted() {
this.getUser();
this.debugItem.extra1_int = ***how to put here userID?***; ❌
},
methods: {
getUser() {
axios.get('/user')
.then(response => {
this.user = response.data;
this.debugItem['extra1_int'] = this.user.id; ✅
})
.catch(error => console.log(error));
}
}

Related

Array is empty after api call using vuejs3

I'm using vue-js and i encountered this problem where i call a get all api and then store it in an array. The logic works perfectly fine in the first component, however when i copied literally the exact same code and pasted it in a second component the call for some reason returns an empty array instead of the array of users. Here is the component
import UsersInServiceCenterService from "../services/UsersInServiceCenterService";
import UserService from "../services/UserService";
export default {
name: "service center",
data() {
return {
currentServiceCenter: null,
message: '',
listOfSpecificServiceCenter1: [],
listOfSpecifiedUsers1: [],
id:"",
};
},
methods: {
getServiceCenter(id) {
ServiceCenterService.get(id)
.then((response) => {
this.currentServiceCenter = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
updateServiceCenter() {
ServiceCenterService.update(this.currentServiceCenter.id, this.currentServiceCenter)
.then((response) => {
console.log(response.data);
this.message = "The service center was updated successfully!";
})
.catch((e) => {
console.log(e);
});
},
deleteServiceCenter() {
ServiceCenterService.delete(this.currentServiceCenter.id)
.then((response) => {
console.log(response.data);
this.$router.push({ name: "service centers" });
})
.catch((e) => {
console.log(e);
});
},
retrieveAllUsersByServiceCenterId(currentServiceCenter){
UsersInServiceCenterService.getAllUsersByServiceCenterId(currentServiceCenter.id)
.then((response) => {
this.listOfSpecificServiceCenter1 = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
retrieve(){
this.retrieveAllUsersByServiceCenterId(this.currentServiceCenter);
if(this.listOfSpecificServiceCenter1.length!=0){
for(var i =0 ; i<this.listOfSpecificServiceCenter1.length;i++){
UserService.get(this.listOfSpecificServiceCenter1[i].userId)
.then((response) => {
this.listOfSpecifiedUsers1.push(response.data);
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
}
}
this.isEmpty = !this.isEmpty;
},
},
mounted() {
this.message = "";
this.getServiceCenter(this.$route.params.id);
},
};
</script>
getServiceCenter(id) works fine and it returns the service center. However both of the retrieve() and the retrieveAllUsersByServiceCenterId(currentServiceCenter) do not work at all and they return the empty array. Here is the first component which works totally fine with literally the exact same functions.
import UserService from "../services/UserService";
import UsersInServiceCenterService from "../services/UsersInServiceCenterService";
export default {
name: "servicecenters-list",
data() {
return {
serviceCenters: [],
users:[],
currentServiceCenter: null,
currentUser: null,
currentIndex: -1,
currentUserIndex: -1,
id: "",
searchValue: "",
isEmpty: false,
rows: [],
listOfSpecificServiceCenter:[],
listOfSpecifiedUsers:[],
};
},
methods: {
retrieveServiceCenters() {
ServiceCenterService.getAllServiceCenters()
.then((response) => {
this.serviceCenters = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
retrieveUsers() {
UserService.getAllUsers()
.then((response) => {
this.users = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
refreshList() {
this.retrieveServiceCenters();
//this.retrieveUsers();
this.currentServiceCenter = null;
this.currentIndex = -1;
//this.currentUser = null;
//this.currentUserIndex = -1;
},
setActiveServiceCenter(servicecenter, index) {
this.currentServiceCenter = servicecenter;
this.currentIndex = index;
},
setActiveUser(user,userIndex){
this.currentUser= user;
this.currentUserIndex = userIndex;
},
// showList(currentServiceCenter){
// for(var i =0;i<currentServiceCenter.users.length;i++){
// }
// },
retrieve(){
this.retrieveAllUsersByServiceCenterId(this.currentServiceCenter);
if(this.listOfSpecificServiceCenter.length!=0){
for(var i =0 ; i<this.listOfSpecificServiceCenter.length;i++){
UserService.get(this.listOfSpecificServiceCenter[i].userId)
.then((response) => {
this.listOfSpecifiedUsers.push(response.data);
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
}
}
this.isEmpty = !this.isEmpty;
},
retrieveAllUsersByServiceCenterId(currentServiceCenter){
UsersInServiceCenterService.getAllUsersByServiceCenterId(currentServiceCenter.id)
.then((response) => {
this.listOfSpecificServiceCenter = response.data;
console.log(response.data);
})
.catch((e) => {
console.log(e);
});
},
addUserToServiceCenter(currentServiceCenter, currentUser) {
var data = {
serviceCenterId: parseInt(this.currentServiceCenter.id),
userId: parseInt(this.currentUser.id),
};
UsersInServiceCenterService.add(data)
.then((response) => {
//this.currentServiceCenter.id = response.data.id; //take care here
console.log(response.data);
this.submitted = true;
})
.catch((e) => {
console.log(e);
});
this.show=false
if(currentServiceCenter.users == Array.isArray(currentServiceCenter.users))
//currentServiceCenter.users = Array.isArray(currentServiceCenters.users) : [...currentServiceCenter.users, currentUser] : [currentUser]
currentServiceCenter.users.push(currentUser);
else{
currentServiceCenter.users = []
currentServiceCenter.users.push(currentUser);
}
},
removeAllServiceCenters() {
ServiceCenterService.deleteAllServiceCenters()
.then((response) => {
console.log(response.data);
this.refreshList();
})
.catch((e) => {
console.log(e);
});
},
searchId(id) {
ServiceCenterService.get(id)
.then((response) => {
this.currentServiceCenter = response.data;
})
.catch((e) => {
console.log(e);
});
this.refreshList();
// if(typeof id ==='string'){
// }
// else if(typeof id==='number'){
// CompanyService.get(id).then(response =>{
// this.currentCompany=response.data
// })
// .catch(e=>{
// console.log(e);
// });
// }
},
},
mounted() {
this.retrieveServiceCenters();
this.retrieveUsers();
},
computed:{
usersFilteredListByName(){
if(this.searchValue.trim().length >0){
return this.serviceCenters.filter((servicecenter) =>servicecenter.name.toLowerCase().includes(this.searchValue.trim()))
}
// if(this.searchValue.length>0 && isNaN(parseInt(this.searchValue))){
// return this.companies.filter((company) =>company.id.includes(this.searchValue))
// }
return this.serviceCenters
},
usersFilteredListById(){
if(this.searchValue.trim().length >0){
return this.serviceCenters.filter((servicecenter) =>servicecenter.id.toString().includes(this.searchValue))
}
return this.serviceCenters
},
}
};
</script>
You can ignore the rest of the functions and focus on the retrieve() and retrieveAllUsersByServiceCenterId(). Any help would be highly appreciated.

Vue js the field in data() was not initialized by call of second (help) function

I don't have almost any experience with vue js.
I have 2 functions loadComponentsOfUser() and loadUserId(), so that loadComponentsOfUser() uses the userID field, which must be loaded by the loadUserId() function.
data() {
return {
userId: ''
}
},
created() {
this.loadComponentsOfUser()
},
methods(): {
loadUserId() {
axios.get('getUserId').then(res => {
this.userId = res.data
}).catch(() => {
...
})
});
},
loadComponentsOfUser() {
this.loadUserId()
axios.get('users/' + this.userId).then(res => {
}).catch(() => {
...
})
});
}
The loadUserId() function works correctly and loads the correct value from the server
But when loadComponentsOfUser() is called, the this.userId field looks like it has not been initialized and an empty field comes to the axios.
my question is why the field was not initialized after calling loadUserId()?
You need to wait for responses, yo can use async and await:
new Vue({
el: '#demo',
data() {
return {
id: 1,
userId: '',
user: null
}
},
created() {
this.loadComponentsOfUser()
},
methods: {
async loadUserId() {
await axios.get('https://jsonplaceholder.typicode.com/users/' + this.id)
.then((res) => {
this.userId = res.data.id
})
.catch(() => {})
},
async loadComponentsOfUser() {
await this.loadUserId()
if(this.userId) {
axios.get('https://jsonplaceholder.typicode.com/users/' + this.userId)
.then(res => {
this.user = res.data
})
.catch(() => {})
}
}
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js" integrity="sha512-odNmoc1XJy5x1TMVMdC7EMs3IVdItLPlCeL5vSUPN2llYKMJ2eByTTAIiiuqLg+GdNr9hF6z81p27DArRFKT7A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="demo">
<input type="number" v-model="id" /><button #click="loadComponentsOfUser">load</button>
{{ user }}
</div>

Problem when calling the helper function - Vue

Main view:
<script>
import { testMethod1 } from "../helper";
export default {
methods: {
init(){
console.log("Res:", testMethod1());
}
}
}
</script>
Helper:
import DataService from "../services/data.service";
export function testMethod1() {
DataService.getByPage()
.then((response) => {
console.log(response)
return response;
})
.catch((error) => {
console.log(error);
})
}
Output:
From view:
Res: undefined
From helper:
0: {_id: "60b621b4809e4304e04e7df4", desc: "aaa", …}
1: {_id: "60b621b4809e4304e04e7df5", desc: "bbb", …}
(..)
What am I doing wrong?
// See this is the same error
const incorrectFoo = () => {
fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => json)
}
const correctFoo = () => {
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => json)
}
const someOtherFoo = async () => {
console.log('incorrect foo', await incorrectFoo(), 'correctFoo', await correctFoo())
}
someOtherFoo()
This method is executing a async call,
export function testMethod1() {
DataService.getByPage()
.then((response) => {
console.log(response)
return response;
})
.catch((error) => {
console.log(error);
})
}
Now if you notice DatasService is a async call and that async call get to another context where it whenever get resolved returns response which mean testMethod1 is not returning anything any way try this
export function testMethod1() {
return DataService.getByPage()
.then((response) => {
console.log(response)
return response;
})
.catch((error) => {
console.log(error);
})
}
<script>
import { testMethod1 } from "../helper";
export default {
methods: {
async init(){
console.log("Res:", await testMethod1());
}
}
}
</script>
After importing the method from helper, you need also to declare it in methods section like:
<script>
import { testMethod1 } from "../helper";
export default {
methods: {
testMethod1, // this is same with testMethod1: testMethod1,
init(){
console.log("Res:", this.testMethod1());
}
}
}
</script>

Nativescript Vue - function is blocking DOM

I've got a nativescript vue application, and on a certain page I need to fetch some data (every 3 seconds) from an api using axios. The data is returned in xml, and I convert it to json using xml2js. I'm using async/await for both these functions. Something is blocking the UI thread, because whenever this function runs scrolling in my app freezes, along with any animations.
Does anyone know what here is blocking the DOM?
<template>
//ui code here
</template>
<script>
import { mapGetters } from 'vuex'
import axios from 'axios'
import xml2js from 'nativescript-xml2js'
export default {
name: 'component1',
data () {
return {
pending: true,
error: false,
results: null,
refreshInterval: null
}
},
computed: {
...mapGetters({
token: 'main/token'
})
},
methods: {
async requestData() {
const headers = {
Cookie: 'USER_ID=' + this.token
}
const url = 'url goes here'
const parser = new xml2js.Parser({
async: true
})
try {
const response = await axios.get(url, { headers: headers })
const newData = await new Promise((resolve, reject) => parser.parseString(response.data, (err, result) => {
if (err) reject(err)
else resolve(result)
}))
this.results = newData['results']
this.error = false
this.pending = false
} catch (e) {
this.data = null
this.error = e
this.pending = false
}
this.pending = false
}
},
created() {
setTimeout(() => {
this.requestData()
},500)
this.refreshInterval = setInterval(() => {
this.requestData()
},3000)
},
beforeDestroy () {
clearInterval(this.refreshInterval)
}
}
</script>
EDIT:
I tried implementing workers to offload xml2js to another thread, but still having the same issue. This is how my code looks now:
home.vue:
<template>
<template/>
<script>
import { mapGetters } from 'vuex'
export default {
name: 'component1',
data () {
return {
dataLoaded: true,
error: false,
results: null,
refreshInterval: null
}
},
computed: {
...mapGetters({
token: 'main/token'
})
},
methods: {
requestData() {
console.log('fetching....')
this.$backendService
.api()
.then(xml => {
return this.$backendService.x2jworker(xml)
})
.then(json => {
if( this.results !== json['results'] ) {
this.results = json['results']
}
this.dataLoaded = true
this.error = false
})
.catch((error) => {
this.dataLoaded = true
this.error = true
})
}
},
created() {
setTimeout(() => {
this.requestData()
},500)
this.refreshInterval = setInterval(() => {
this.requestData()
},3000)
},
beforeDestroy () {
clearInterval(this.refreshInterval)
}
}
</script>
backend-service.js:
import axios from 'axios';
import xml2js from 'nativescript-xml2js'
import { WorkerService } from "../worker.service"
export default class BackendService {
api() {
return new Promise((resolve, reject) => {
const url = 'url'
axios.get(url)
.then(response => {
resolve(response.data)
})
.catch((error) => {
if (error) {
console.log('uh oh')
reject(error)
}
})
})
}
x2jworker(xml) {
return new Promise((resolve, reject) => {
var workerService = new WorkerService()
var jsWorker = workerService.initJsWorker()
jsWorker.onmessage = m => {
resolve(m.data)
}
jsWorker.postMessage(xml)
jsWorker.onerror = e => {
console.log(e)
jsWorker.terminate()
reject(e)
}
})
}
}
worker/javascript.worker.js:
import 'tns-core-modules/globals'
import xml2js from 'nativescript-xml2js'
global.onmessage = function (msg) {
console.log("Inside JS worker...")
var parser = new xml2js.Parser({
async: true
})
parser.parseString(msg.data, function (err, result) {
if (err) {
console.log(err)
global.close()
} else {
global.postMessage(result)
}
})
}
worker-service.js:
const workers = []
export class WorkerService {
constructor() {
}
initJsWorker() {
if (this.jsWorker) {
return this.jsWorker
}
const JsWorker = require("nativescript-worker-loader!./workers/javascript.worker.js")
this.jsWorker = new JsWorker()
workers.push(this.jsWorker)
return this.jsWorker
}
}
if ((module).hot) {
(module).hot.dispose(() => {
workers.forEach(w => {
w.terminate()
})
})
}

api call not working properly

I am trying to do a simple to do app that does a request to a pokemon api and send me the result.
like this:
<template>
<div id="app">
<div>{{pokemon.forms}}</div>
</div>
</template>
<script>
import axios from "axios";
export default {
name: "app",
data() {
return {
pokemon: {}
};
},
methods: {
requestPokemon() {
return new Promise((resolve, reject) => {
axios.get("http://pokeapi.co/api/v2/pokemon/2").then(value => {
resolve(value);
})
.catch(error => {
reject(error);
})
});
}
},
beforeMount() {
this.requestPokemon().then(value => {
pokemon = value;
}).error(error => {
console.log(error);
})
}
};
</script>
<style>
</style>
the issue is that i get the following error:
Error in beforeMount hook: "TypeError: this.requestPokemon(...).then(...).error is not a function"
any help with this??
thanks
Replace error with catch, as the others said:
export default {
name: "app",
data() {
return {
pokemon: {}
};
},
methods: {
requestPokemon() {
return new Promise((resolve, reject) => {
axios.get("http://pokeapi.co/api/v2/pokemon/2").then(value => {
resolve(value);
})
.catch(error => {
reject(error);
})
});
}
},
beforeMount() {
this.requestPokemon().then(value => {
pokemon = value;
}).catch(error => {
console.log(error);
})
}
};
Your beforeMount is not correct.
As oMiKeY said in his answer, you need to change .error to .catch
You also need to bind the response to this.pokemon (and not just pokemon)
Then, as requestPokemon function returns a Promise, you need to find the data in it :
beforeMount() {
this.requestPokemon().then(value => {
this.pokemon = value.data
}).catch(error => {
console.log(error);
})
}

Categories

Resources