Buefy Axios autocompletion - vue.js

We're trying to use the Buefy autocomplete with our Api and the API says that it needs an Object, no matter what we try, the text we type in the input won't accepted, it will though if we hard code it but that's obviously not an option. We're not sure how to change the code so it gives us the suggestions from the API. We're still in apprenticeship and are pretty lost at the moment.
We tried different approaches but none of them seem to work, any help would be greatly appreciated
<b-field>
<b-autocomplete
v-model="text"
:data="data"
placeholder="e.g. Java"
field="title"
:loading="isFetching"
#typing="newPost()"
#select="(selected) => addSkill(selected)"
>
</b-autocomplete>
</b-field>
<script>
/* import debounce from "lodash/debounce"; */
import axios from "axios";
export default {
data() {
return {
data: [],
skills: [],
selected: "",
isFetching: false,
text: "",
};
},
methods: {
newPost(data) {
const session_url =
"Link to API";
const config = {
auth: {
username: ,
password: ,
},
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
};
data = { text: "" };
axios
.post(session_url, data, config)
.then(function (response) {
console.log("Authenticated");
console.log(data);
response.data = [];
response.data.forEach((data) => this.data.push(data));
})
.catch(function () {
console.log("Error on Authentication");
});
},
addSkill(data) {
if (data != null) this.skills.push(data.title);
return;
},
deleteSkill: function (skill) {
this.skills.splice(skill, 1);
},
},
};
</script>

Related

Test vue watcher in jasmine which triggers a fetch method

I've implemented a small autocomplete which fetches information based upon the search input. In the frontend everythign works fine but when I try to test my watcher it always states that the items array is empty. I guess something in my async/await structure in the test is wrong but I cannot figure out what it is.
<template>
<v-autocomplete
v-model="inputText"
:items="items"
:search-input.sync="search"
></v-autocomplete>
</template>
<script>
export default {
name: 'Autocomplete',
data() {
return {
items: [],
inputText: '',
search: '',
};
},
watch: {
search(val) {
this.getDataFromApi(val);
},
},
methods: {
getDataFromApi(val) {
this.loading = true;
return fetch(
'https://jsonplaceholder.typicode.com/todos/' +
val
)
.then(response => response.json())
.then(data => {
this.items.push(data);
})
.finally(() => {
this.loading = false;
});
},
},
};
</script>
it('validates the Autocomplete properties', async function(done) {
// GIVEN an instantiated Search
const wrapper = shallowMount(Autocomplete, {
localVue: this.localVue,
propsData: mockProps,
});
await wrapper.setData({ search: 'asdf' });
expect(wrapper.vm._data.items).toEqual([
{
"userId": 1,
"id": 1,
"title": "delectus aut autem",
"completed": false
}
]);
});

How to fetch data in Vue 3?

I don't know how to fetch data with Vue 3? I created one action and with this action I am calling endpoint (https://api.openbrewerydb.org/breweries/5494). I didn't get response data.
Endpoint:
import { createStore } from 'vuex'
export default createStore({
state: {
},
mutations: {
},
actions: {
async getData() {
await fetch('https://api.openbrewerydb.org/breweries/5494', {
method: 'get',
headers: { 'Content-type': 'application/json' },
}).then((response) => {
if (!response.ok) {
throw Error(response.statusText);
}
console.log('response: ', response)
}).catch((error) => {
console.log('Looks like there was a problem: \n', error);
});
}
},
modules: {
}
})
Vue component:
<template>
<div #click="loadData">Load Data</div>
</template>
<script>
import { useStore } from 'vuex'
export default {
name: 'HelloWorld',
props: {
msg: String
},
setup () {
const store = useStore()
const loadData = () => {
store.dispatch('getData')
}
return { loadData }
}
}
</script>
As a response I didn't get anything but I should get:
{"id":5494,"name":"MadTree Brewing","brewery_type":"regional","street":"3301 Madison Rd","address_2":null,"address_3":null,"city":"Cincinnati","state":"Ohio","county_province":null,"postal_code":"45209-1132","country":"United States","longitude":"-84.4239715","latitude":"39.1563725","phone":"5138368733","website_url":"http://www.madtreebrewing.com","updated_at":"2018-08-24T15:44:22.281Z","created_at":"2018-07-24T01:34:01.620Z"}
You need to make the data to json
.then(res=>res.json())
this will do the trick for you.
const getData = () => {
fetch('https://api.openbrewerydb.org/breweries/5494', {
headers: { 'Content-type': 'application/json' },
}).then(res=>res.json()).then((response) => {
console.log({ response })
}).catch((error) => {
console.log('Looks like there was a problem: \n', error);
});
}
getData();
If the response fails, it will surely get you to catch.
This answer Should be the accepted answer.
If readers landed here while working through the introductory examples on the Vue.js website, Adarsh's code can be adapted thusly (for Vue.js 3):
<div id="beer">
{{ message }}
</div>
const Breweries = {
data() {
return {
message: ""
}},
mounted() {
fetch('https://api.openbrewerydb.org/breweries/', {
headers: { 'Content-type': 'application/json' },
}).then(res=>res.json()).then((response) => {
this.message = response;
}).catch( (error) => {
this.message = error;
});
}
}
Vue.createApp(Breweries).mount('#beer')
First you must install a package like axios
Then create an object from axios and call the API
import axios from "axios";
export default {
setup() {
function getUsers() {
axios.get("https://jsonplaceholder.typicode.com/users")
.then(function (response) {
// handle success
console.log(response.data);
})
.catch(function (error) {
// handle error
console.log(error);
});
getUsers();
}
return { getUsers };
},
};

TypeError: stripe.redirectToCheckout is not a function in nuxt.js

I am trying to integrate stripe payment gateway. I have a nuxt.js for front-end and adonis.js for backend.
From front-end I am calling an api to backend to create checkoutSession and return the sessionID. I am able to create checkoutSession and return the sessionID and in api response I am calling the
stripe.redirectToCheckout but it is not redirecting rather gives error as stripe.redirectToCheckout is not a function. How can I redirect users to checkout Page?
I have install the stripe-js file also.
import { loadStripe } from '#stripe/stripe-js'
const stripe = loadStripe(process.env.STRIPE_PK)
<button class="btn btn-primary btn-block text-center rounded" #click="checkout()">Buy</button>
import { loadStripe } from '#stripe/stripe-js'
const stripe = loadStripe(process.env.STRIPE_PK)
export default {
methods: {
checkout() {
let params = {
payment_method_types: ['card'],
line_items: [
{
name: 'Buy Now',
images: ['image.jpg'],
amount: 100 + '00',
currency: 'usd',
quantity: 1,
},
],
mode: 'payment',
success_url: `${process.env.URL}/success`,
cancel_url: window.location.href,
}
axios
.post(`${process.env.API_BASE_URL}/stripe/session`, params, {
'Content-type': 'application/json',
Accept: 'application/json',
})
.then((response) => {
this.stripeSession = response.data.data
stripe.redirectToCheckout({sessionId: this.stripeSession})
})
.catch((e) => {
console.log(e)
})
}
},
}
</script>
According to tyhe doc, loadStripe is an async function, try adding await in stripe assignement:
const stripe = await loadStripe(process.env.STRIPE_PK)
Edit:
To get rid of Module parse failed: Cannot use keyword 'await' outside an async function error you just need to add async before your function declaration :
async function myAsyncFunction() {
const test = await myPromise();
}
As I do not have the full definition of your function I cannot show it to you in your code :-(
But a weird solution (mixing 'await' and 'then') would be :
import { loadStripe } from '#stripe/stripe-js';
axios
.post(`${process.env.API_BASE_URL}/stripe/session`, params, {
'Content-type': 'application/json',
Accept: 'application/json',
})
.then(async response => {
this.stripeSession = response.data.data;
const stripe = await loadStripe(process.env.STRIPE_PK);
stripe.redirectToCheckout({ sessionId: this.stripeSession });
})
.catch(e => {
console.log(e);
});
This should work:
import { loadStripe } from '#stripe/stripe-js';
export default {
methods: {
async checkout() {
let params = {
payment_method_types: ['card'],
line_items: [
{
name: 'Buy Now',
images: ['image.jpg'],
amount: 100 + '00',
currency: 'usd',
quantity: 1,
},
],
mode: 'payment',
success_url: `${process.env.URL}/success`,
cancel_url: window.location.href,
};
try {
const { data } = await axios.post(`${process.env.API_BASE_URL}/stripe/session`, params, {
'Content-type': 'application/json',
Accept: 'application/json',
});
this.stripeSession = data.data;
const stripe = await loadStripe(process.env.STRIPE_PK);
stripe.redirectToCheckout({ sessionId: this.stripeSession });
} catch (error) {
console.error(error);
}
},
},
};

Access Vue app (this) from non vue file

I'm new to vue (started using vue 2) I'm using Store (vuex) and I'm trying to acheive something.
basically I managed to install the vue-auth plugin : I have this.$auth that I can call from within .vue files.
Now using the store I wanna call the userLogin function by dispatching the call like this from a vue file :
<script>
export default {
computed: {
comparePasswords() {
return this.password === this.passwordConfirm
? true
: "Passwords don't match";
}
},
methods: {
userSignUp() {
if (this.comparePasswords !== true) {
return;
}
this.$store.dispatch("userSignUp", {
email: this.email,
password: this.password
});
}
},
data() {
return {
email: "",
password: "",
passwordConfirm: ""
};
}
};
</script>
in the store/index I'm trying to access the 'this.$auth' I do understand is some kind of context switching but I don't know how to access the vue app instance. :
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
let app = this
export const store = new Vuex.Store({
state: {
appTitle: 'LiveScale Dashboard',
user: null,
error: null,
loading: false
},
mutations: {
setUser(state, payload) {
state.user = payload
},
setError(state, payload) {
state.error = payload
},
setLoading(state, payload) {
state.loading = payload
}
},
actions: {
userLogin({ commit }, payload) {
commit('setLoading', true)
var redirect = this.$auth.redirect(); // THIS IS WRONG.
this.$auth.login({ // THIS IS WRONG.
body: payload, // Vue-resource
data: payload, // Axios
rememberMe: this.data.rememberMe,
redirect: { name: redirect ? redirect.from.name : 'account' },
fetchUser: this.data.fetchUser
})
.then(() => {
commit('setUser', this.context)
commit('setLoading', false)
router.push('/home')
}, (res) => {
console.log('error ' + this.context);
commit('setError', res.data)
commit('setLoading', false)
});
},
userSignUp({ commit }, payload) {
// ...
}
},
getters: {}
})
Thanks for your help
try using Vue.$auth in index.js it should work
The idea (so far) is to pass the instance as an argument to the function as follows :
this.$store.dispatch("userSignUp", {
email: this.email,
password: this.password,
auth: this.$auth //added this line
});
and then in the store -> actions , payload.auth will contain my auth plugin :
userLogin({ commit }, payload) {
commit('setLoading', true)
var redirect = payload.auth.redirect();
payload.auth.login({
body: payload, // Vue-resource
data: payload, // Axios
rememberMe: this.data.rememberMe,
redirect: { name: redirect ? redirect.from.name : 'account' },
fetchUser: this.data.fetchUser
})
.then(() => {
commit('setUser', this.context)
commit('setLoading', false)
router.push('/home')
}, (res) => {
console.log('error ' + this.context);
commit('setError', res.data)
commit('setLoading', false)
});
},
I don't know if it's the best practice or not, but this is how I managed to do it. Please feel free to suggest anything.

how to append axios data with good table in vue

guys, I m new to Vue so don't know how to solve this let me first show code then the problem, I m using Vue-Good-table here is link https://xaksis.github.io/vue-good-demos/#/simple-table
<vue-good-table
title="Product List"
:columns="columns"
:rows="rows"
:paginate="true"
:lineNumbers="true" />
export default {
data(){
return {
columns: [
{
label: 'productname',
field: 'product_name',
filterable: true,
},
{
label: 'productdesc',
field: 'product_desc',
// type: 'number',
html: false,
filterable: true,
},
],
rows:[],//get axios return value
};
},
methods:{
next() {
var _this=this
this.$http.get('http://localhost:3000/api/companyproducts')
.then(function (response) {
_this.rows=response.data
})
.catch(function (error) {
});
}
}
}
now my problem is that how i can append this axios responded value with rows of good table
To "append axios data" you have to install axios first in your project.
So first install axios to your project:
npm install --save axios
Then transform your next method into the follow:
next() {
axios.get('http://localhost:3000/api/companyproducts')
.then(response => {
this.rows = response.data
})
.catch(error => console.log(error))
}
Note that you have also to import axios.So when the script tag starts use:
import axios from 'axios'
Axios is a great package you can learn more here
As i can see in your code you are not using axios but vue-resource.Vue-resource is also good package so you can learn more here
I'm guessing with the code you have, the view does not respond after the http.get completes.
You may be able to do it by configuring rows as a computed property, since this watches it's dependents (i.e row_data) for changes
computed: {
rows: function () {
return this.row_data;
}
}
...
data(){
return {
columns: [
...
],
row_data:[]
};
}
...
methods: {
next() {
var _this=this
this.$http.get('http://localhost:3000/api/companyproducts')
.then(function (response) {
_this.row_data = response.data
})
}
}
...
created: function() {
this.next()
}