Get source in constructor - javascript

I'm trying to make a search with autocomplete, tell me how I can get in the constructor an array of label and results with axios get
new Autocomplete(input, {
source: (response) => {
axios.get('{{ route('api.autocomplete) }}', {
params: {
term: input.value
}
})
.then(response => {
return {
label: response.data.name,
results: response.data.children,
}
})
},
select: ({element}) => {
alert(element);
}
});
class Autocomplete {
constructor(element, {
source = () => {},
select = () => {},
}) {
console.log(source);
}
}
Instead of an array, it gives out a piece of axios request code

Related

How to display this data from console.log(element.faculty_name) to template in vue?

I have the function of display data from major table on MySQL. I want to display the type of that major by comparing with the id of the faculty table like below. I have it displayed on console.log, how do I display it on the template?
Template tag
<td>
{{ filterFaculty }}
</td>
Script tag
data() {
return {
majors:[],
faculties:[],
form: new Form({
major_id:'',
major_code:'',
major_name:'',
major_faculty:'',
major_status: '',
}),
};
},
computed: {
filterFaculty() {
for(let i in this.majors) {
this.faculties.forEach((element) => {
if(element.faculty_code==this.majors[i].major_faculty) {
console.log(element.faculty_name);
}else {
return '-';
}
});
}
}
},
mounted() {
this.fetchFaculties();
this.fetchMajors();
},
methods: {
fetchFaculties(page_url) {
let vm = this;
page_url = '../../api/admin/edu-faculty/faculty/faculty';
fetch(page_url)
.then(res => res.json())
.then(res => {
this.faculties = res.data;
})
.catch(err => console.log(err));
},
fetchMajors(page_url) {
let vm = this;
page_url = '../../api/admin/edu-major/major/'+this.currentEntries+'?page='+this.pagination.current_page;
fetch(page_url)
.then(res => res.json())
.then(res => {
this.majors = res.data;
this.pagination = res.meta;
})
.catch(err => console.log(err));
},
}
There are different ways to achieve that, I think the easiest is to do following:
Define something in your data - like inputText and than set your element.faculty_name to this - like following:
data() {
return {
inputText: "",
}
}
computed: {
filterFaculty() {
for(let i in this.majors) {
this.faculties.forEach((element) => {
if(element.faculty_code==this.majors[i].major_faculty) {
this.inputText = element.faculty_name; //Changed here
}else {
return '-';
}
});
}
}
},
and than reference it in your template like this:
<td>
{{ inputText }}
</td>
This should solve your problem!

Axios - cannot change variable data value

I tried to change the variable data using axios, i am using vue-axios and vue cli 3.
This is the code:
const qs = require('qs')
export default {
name: 'Home',
data: function () {
return {
email: null,
errEmail: false,
baseUrl: 'https://www.example.com/isemail.php'
}
},
methods: {
next: function () {
},
err: function () {
this.axios.post(this.baseUrl + 'functions/isEmail.php', qs.stringify({
value: this.email
}))
.then(function (resp) {
this.errEmail = true
})
}
}
}
<div v-if="errEmail">Target Success</div>
Actually i am trying change the errEmail variable depend on the server callback like this:
this.errEmail = resp.data.isemail
but using constant seems not working too.
Change this
.then(function (resp) {
this.errEmail = true
})
to this
.then((resp) => {
this.errEmail = true
})
Or manually bind this
.then(function (resp) {
this.errEmail = true
}.bind(this))

Get axios call in reactjs

Below is the response I am getting after doing get call:
{
    "id": “12345”,
    “details”: {
        “name”: “sample doc”,
        “market: “sample market”
    }
}
My Service Method:
ENDPOINTS = {
product: "/market/product",
}
getDetails(
id: string
): Promise<{
id: string;
}> {
const url = `${this.ENDPOINTS.PRODUCT}/${id}/name`;
return http
.get(url)
.then((response) => {
return response.data;
})
.catch((error) => {
throw error;
});
}
My component Method:
getTestingDone = () => {
this.sampleService
.getDetails(
this.props.product.id,
)
.then((response) => {
this.setState({
});
})
.catch((error) => {
console.log(error);
});
};
<TextInput
labelText="name"
type="text"
name="keyname"
value = {name}
/>
I want to print the response in this input field. Not sure How to get the response from the server to the UI. Can anyone help me with this.Do i need to make a model class? and return it in response in service method?
constructor() {
this.state = {
name: ''
}
}
getTestingDone = () => {
this.sampleService
.getDetails(this.props.product.id)
.then(({details: {name}}) => {
this.setState(state => ({...state, name}));
})
}
render() {
const { name } = this.state;
return <TextInput
labelText="name"
type="text"
name="keyname"
value = {name}/>
}
This is the correct answer for the above question:
constructor(){
this.state = {
details: {
name: "",
market: "",
}
}
getTestingDone = () => {
this.sampleService
.getDetails(this.props.product.id)
then((response) => {
this.setState({
credentials: response.credentials,
});
})
return <TextInput
labelText="name"
type="text"
name="keyname"
value = {this.state.details.name}/>
}
}

Laravel: Uncaught (in promise) Error: Request failed with status code 422

Hi, currently I facing this issue. I can fix it. I have no idea why the error occurs.
Basically, I trying to save the data into DB. I used the Axios method to fetch and save data. Before this, the function was working perfectly but suddenly its causing problems. Please, anyone help me with this.
Vue.js
<script>
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import MarkdownIt from 'markdown-it'
import ClassicEditor from '#ckeditor/ckeditor5-build-classic';
var msg_editor;
Vue.use(VueAxios, axios);
const md = new MarkdownIt({
linkify: true
})
// Vue.directive('select2', {
// inserted(el) {
// $(el).on('select2:select', () => {
// const event = new Event('change', { bubbles: true, cancelable: true });
// el.dispatchEvent(event);
// });
// },
// });
// $('#condition').select2();
export default {
props: ['email_creation_link', 'email_index_route', 'email_edit_route','conditions','modules','mailtemplates'],
components: {
},
data() {
return {
template:
{
subject: '',
message: '' ,
days: '',
condition_id: 1,
},
options:[
{
display:'Client Name',
actual:'Client name'
},
{
display:'Joined Date',
actual:'Joined date'
},
{
display:'Module Name',
actual:'Module name'
},
{
display:'Last Seen',
actual:'Last seen'
},
],
showName: false,
}
},
mounted(){
var self = this;
ClassicEditor
.create(document.querySelector( "#msg"),
{
})
.then(editor => {
msg_editor = editor;
editor.model.document.on( 'change:data', () => {
self.template.message = msg_editor.getData();
});
})
.catch(error => {
console.error(error);
})
if (this.mailtemplates) {
this.template=this.mailtemplates;
}
},
methods: {
//Drag items
dragstart: function(item, e){
this.draggingItem = item;
e.dataTransfer.setData('text/plain', item.actual);
},
dragend: function(item,e) {
e.target.style.opacity = 1;
},
dragenter: function(item, e) {
this.draggingItem = item;
},
//content
replaceVariables(input)
{
let updated = input
return updated
},
//hidecontent
showHide: function(e)
{
console.log("Show "+e.target.value+ " fields")
this.showName = e.target.value == '3'
},
fetch()
{
//request data
axios.get(this.email_creation_link,this.template)
.then((res) => {
this.template = res.data.template;
})
},
save()
{
//save data to db
axios.post(this.email_creation_link, this.template)
.then((res) => {
alert('Mail sent successfull!')
})
},
addToMail: function(type, text)
{
if (type == 'message') {
this.template.message += text;
msg_editor.setData(this.template.message);
}
},
//user name replace
replaceVariables() {
return this.replaceVariables(this.options || '')
},
},
}
</script>
route.php
Route::post('api/email/create', ['as' => 'email.create', 'uses' => 'Havence\AutoMailController#create']);
Route::get('automail/mail',['as'=>'email.mail','uses' => 'Havence\AutoMailController#mail']);
Route::get('automail/index',['as'=>'email.index','uses' => 'Havence\AutoMailController#index']);
Route::get('automail/edit/{id}',['as'=>'email.edit','uses' => 'Havence\AutoMailController#edit']);
Route::get('automail/delete',['as'=>'email.delete','uses' => 'Havence\AutoMailController#destroy']);

How to use settimeout with vue.js watchers?

I have custom watcher for search field in my application:
watch: {
search (query) {
if(query.length > 2) {
axios.post(url, query)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
}
}
Here as you see I've send request to server on everey change value of search var in my case. I tired paste my code inside setTimeout but when user typing 3 time then requests too sent 3 times instead of one time. I need to wait when user is typing and after stop typing send one request to server.
setTimeout(function () {
// request code here
}, 3000);
How I can do it correctly inside vue.js watchers?
You can use debounce in lodash. It's perfect for your usecase.
import _ from lodash
watch: {
search (query) {
this.performSearch(query)
}
},
methods: {
performSearch: _.debounce(function(query) {
axios.post(url, query)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}, 200)
}
If you want to implement it without lodash library, you can try
data() {
return {
timeoutQuery: null
}
},
watch: {
search (query) {
if (this.timeoutQuery) { clearTimeout(this.timeoutQuery) }
this.timeoutQuery = setTimeout(this.performSearch(query), 300)
}
},
methods: {
performSearch(query) {
axios.post(url, query)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
}
}
You should use any flag to indicate than your request is busy:
data () {
return {
isRequestBusy: false
}
},
watch: {
search (query) {
if(query.length > 2 && !this.isRequestBusy) {
this.isRequestBusy = true
axios.post(url, query)
.then(res => {
console.log(res)
})
.catch(error => {
console.log(error)
})
.finally(() => {
this.isRequestBusy = false
})
}
}
}
You can use the arrow function and put your code inside of it.
data() {
return {
query: "",
queryTimeout: null
};
},
watch: {
query(newValue, oldValue) {
console.log(newValue, oldValue);
const timer = 500; // In miliseconds
if (this.queryTimeout) {
clearTimeout(this.queryTimeout);
}
setTimeout(() => {
this.fetchData(newValue)
}, timer);
}
},
methods: {
fetchData(query = null) {
console.log(query);
// Put your logic code here
}
}
For more way to solve this problem, check this link.
https://stackoverflow.com/a/38431406/4494207

Categories