vue js select (vuetify) + axios population - javascript

I have a stack with vue js (vuetify) + laravel + axios.
I am trying to populate a dropdown select using axios.
I have setup an API route on laravel so I can pull data from database table "Categories".
The api return the following:
[
{
"id": 1,
"category_name": "Electronics",
"category_synonym": "Computer Accessories",
"created_at": "2020-05-31T20:11:56.000000Z",
"updated_at": "2020-05-31T20:11:56.000000Z"
},
{
"id": 2,
"category_name": "Hardware",
"category_synonym": "hardware",
"created_at": "2020-05-31T20:17:13.000000Z",
"updated_at": "2020-05-31T20:17:13.000000Z"
},
{
"id": 3,
"category_name": "Kitchenware",
"category_synonym": null,
"created_at": "2020-05-31T20:49:32.000000Z",
"updated_at": "2020-05-31T20:49:32.000000Z"
},
{
"id": 4,
"category_name": "Textile",
"category_synonym": null,
"created_at": "2020-05-31T21:29:30.000000Z",
"updated_at": "2020-05-31T21:29:30.000000Z"
}
]
I would like to put the category_name into a vue js dropdown contained into a foram.
How to make it simply ?

Vuetify select has item-text and item-value. You can use these props:
<v-select
label="Category"
:items="categories"
item-text="category_name"
item-value="id"
/>

You can try something like this:
<v-select v-model="currentCategory" :items="resultFromAPI" item-text="category_name" item-value="id" />
To fetch the data with Axios you can try something like this:
import axios from 'axios';
const ajax = axios.create({
baseURL: 'https://example.com/api',
headers: {
'Content-Type': 'application/json'
}
});
export default
{
data()
{
return {
categories: [],
currentCategory: null,
}
},
mounted()
{
this.fetchData();
},
methods:
{
fetchData()
{
ajax.get('/categories').then(response =>
{
this.currentCategory = null;
this.categories = response || [];
});
}
}
}

Related

Why are asset attributes missing from Imgix Management API?

I am querying the Imgix Management API with no issue. I can retrieve an individual asset and a list of assets. However, most of the data properties are null. It looks like this:
{
"data": {
"attributes": {
"analyzed_content_warnings": null,
"analyzed_faces": null,
"analyzed_tags": null,
"categories": null,
"color_model": null,
"color_profile": null,
"colors": null,
"content_type": "image/jpeg",
"custom_fields": null,
"date_created": 1667935028,
"date_modified": null,
"description": null,
"dpi_height": null,
"dpi_width": null,
"face_count": null,
"file_size": 1016205,
"has_frames": null,
"media_height": null,
"media_kind": "IMAGE",
"media_width": null,
"name": null,
"origin_path": "/test/roses.jpeg",
"source_id": "XXXXXXXXXXXXXXXXXXXX",
"tags": null,
"uploaded_by": null,
"uploaded_by_api": false,
"warning_adult": null,
"warning_medical": null,
"warning_racy": null,
"warning_spoof": null,
"warning_violence": null
},
"id": "XXXXXXXXXXXXXXXXXXX/test/roses.jpeg",
"type": "assets"
},
"included": [],
"jsonapi": {
"version": "1.0"
},
"meta": {
"authentication": {
"authorized": true,
"clientId": null,
"mode": "PUBLIC_APIKEY",
"modeTitle": "Public API Key",
"tag": "XXXXXXXXXXXXXXX",
"user": null
},
"server": {
"commit": "7c78ee15",
"status": {
"healthy": true,
"read_only": false,
"tombstone": false
},
"version": "3.187.0"
}
}
}
I'm missing data.colors, data.media_height, data.media_width.
My code is very basic:
import fetch from 'node-fetch'
const imgix_key = 'xxxxxxxx'
const imgix_source_id = 'xxxxxxxx'
const imgix_url = `https://api.imgix.com/api/v1/assets/${imgix_source_id}/test/roses.jpeg`
async function init() {
const method = 'get'
const headers = {
Authorization: `Bearer ${imgix_key}`,
'Content-Type': 'application/x-www-form-urlencoded',
}
const response = await fetch(imgix_url, { headers, method })
const body = await response.text()
console.log(body)
}
init()
I can access data.colors if I request this image from the rendering API with the palette=json parameter, so I know the property theoretically exists.
Request to https://xxxxxxx.imgix.net/test/roses.jpeg?palette=json:
{
"colors":[
{
"red":0.960784,
"hex":"#f5ece9",
"blue":0.913725,
"green":0.92549
},
{
"red":0.843137,
"hex":"#d7cb99",
"blue":0.6,
"green":0.796078
},
{
"red":0.768627,
"hex":"#c44535",
"blue":0.207843,
"green":0.270588
},
{
"red":0.670588,
"hex":"#aba544",
"blue":0.266667,
"green":0.647059
},
{
"red":0.454902,
"hex":"#746a4f",
"blue":0.309804,
"green":0.415686
},
{
"red":0.227451,
"hex":"#3a452f",
"blue":0.184314,
"green":0.270588
}
],
"average_luminance":0.387471,
"dominant_colors":{
"vibrant":{
"red":0.698039,
"hex":"#b2524d",
"blue":0.301961,
"green":0.321569
},
"muted_light":{
"red":0.823529,
"hex":"#d2b3aa",
"blue":0.666667,
"green":0.701961
},
"muted":{
"red":0.698039,
"hex":"#b2524d",
"blue":0.301961,
"green":0.321569
},
"vibrant_dark":{
"red":0.368627,
"hex":"#5e220c",
"blue":0.0470588,
"green":0.133333
},
"vibrant_light":{
"red":0.898039,
"hex":"#e5c699",
"blue":0.6,
"green":0.776471
},
"muted_dark":{
"red":0.305882,
"hex":"#4e3529",
"blue":0.160784,
"green":0.207843
}
}
}
I've tried adding a fields parameter, like this:
https://api.imgix.com/api/v1/assets/xxxxxxxxxxxxxx/test/roses.jpeg?fields[assets]=name,origin_path,colors,media_width,media_height
I get the specified properties, but they're still null.
Could anyone help me understand why these properties are coming back null?
I would like to write a prebuild script to cache the image metadata so I can set image dimensions and colorful placeholder blocks.
Thanks
I would encourage you to write into our support team (support#imgix.com) with this issue. The reason these fields return null is likely tied to your account/Source settings, which they can help you navigate. Hope that helps.

How to work with REST API using Ember data?

I'm trying to use ember data with REST API from server. The project is quiet simple and works fine with Fetch API, but i would like to implement the same result using Ember data and understand it's principles. I could not use ember twiddle with this configuration. Below will be the main parts of the project. It was made by Ember CLI version 4.0.1.
The JSON responce from url http://localhost:3000/api/v1/items looks like:
[
{
"id": 1,
"name": "Item 1",
"description": "12345",
"created_at": "2022-01-07T11:43:21.755Z",
"updated_at": "2022-01-07T11:43:21.755Z"
},
{
"id": 2,
"name": "Item 2",
"description": "22222",
"created_at": "2022-01-07T11:43:29.787Z",
"updated_at": "2022-01-07T11:43:29.787Z"
},
{
"id": 3,
"name": "Item 3",
"description": "33333",
"created_at": "2022-01-07T11:43:37.885Z",
"updated_at": "2022-01-07T11:43:37.885Z"
}
]
The responce from a single item request such as http://localhost:3000/api/v1/items/1:
{
"id": 1,
"name": "Item 1",
"description": "12345",
"created_at": "2022-01-07T11:43:21.755Z",
"updated_at": "2022-01-07T11:43:21.755Z"
}
app/models/item.js:
import Model, { attr } from '#ember-data/model';
export default class ItemModel extends Model {
#attr name;
#attr description;
}
app/routes/items.js:
import Route from '#ember/routing/route';
import { inject as service } from '#ember/service';
export default class ItemsRoute extends Route {
#service store;
async model() {
return this.store.findAll('item');
}
}
app/routes/item.js:
import Route from '#ember/routing/route';
import { inject as service } from '#ember/service';
export default class ItemRoute extends Route {
#service store;
async model(params) {
return this.store.findRecord('item', params.id);
}
}
app/templates/items.hbs:
{{#each #model as |item|}}
<LinkTo #route='item' #model={{item}}>{{item.name}}</LinkTo>
{{/each}}
app/adapters/application.js:
import RESTAdapter from '#ember-data/adapter/rest';
export default class ItemAdapter extends RESTAdapter {
host = 'http://localhost:3000';
namespace = 'api/v1';
buildURL(...args) {
return `${super.buildURL(...args)}.json`;
}
}
app/serializers/application.js:
import RESTSerializer from '#ember-data/serializer/rest';
export default class ItemSerializer extends RESTSerializer {}
app/router.js:
import EmberRouter from '#ember/routing/router';
import config from 'dist/config/environment';
export default class Router extends EmberRouter {
location = config.locationType;
rootURL = config.rootURL;
}
Router.map(function () {
this.route('items');
this.route('item', { path: '/:id' });
});
When I move to route /items on the ember client, the following error appears in the console:
WARNING: Encountered "0" in payload, but no model was found for model
name "0" (resolved model name using
<dist#serializer:item::constructor>.modelNameFromPayloadKey("0"))
And the same errors for "1" and "2". The template doesn't render links in the each loop.
Probably, there are some features in Ember data with REST API, and I would really like to figure it out. Thanks for attention!
I believe you have this issue because your data is not in the RESTSerializer format but rather in the JSONSerializer one:
the JSONSerializer expects the response to be a JSON object that looks
similar to this
{
"id": "1",
"title": "Rails is omakase",
"tag": "rails",
"comments": ["1", "2"]
}
So i guess you should just use this one.
If for any reason you wanna keep the RESTSerializer you should return your data similar to this format:
{
"item":
{
"id": 1,
"name": "Item 1",
"description": "12345",
"created_at": "2022-01-07T11:43:21.755Z",
"updated_at": "2022-01-07T11:43:21.755Z"
}
}
or for a list
{
"items": [
{
"id": 1,
"name": "Item 1",
"description": "12345",
"created_at": "2022-01-07T11:43:21.755Z",
"updated_at": "2022-01-07T11:43:21.755Z"
},
...
]

How to get the right API information via JSON using React and Axios

I'm trying to get the Swedish consumer price index (Konsumentprisindex - KPI) from the national statistics website (SCB) via an open API. I'm using React and Axios.
Api: http://api.scb.se/OV0104/v1/doris/en/ssd/PR/PR0101/PR0101A/KPIFastAmed
I don't understand what values in the API will give me the KPI. response.data.variables[1].values[0] only respond the year, but I don't understand how to retrieve the KPI from that specific year.
Thanks in advance, have a great day!
This is my App.js
import React,{useState} from 'react';
import './App.css';
import Axios from 'axios';
function App() {
const [KPI, setKPI] = useState("");
const getKPI = () => {
Axios.get("http://api.scb.se/OV0104/v1/doris/en/ssd/PR/PR0101/PR0101A/KPIFastAmed")
.then((response) => {
console.log(response)
setKPI(response.data.title
+ " " +
response.data.variables[1].values[0])
});
}
return (<div><h1>{KPI}</h1><button onClick={getKPI}>M3</button></div>);
}
export default App;
As the Docs says , You need to send POST request with body that looks like this :
{
"query": [
{
"code": "ContentsCode",
"selection": {
"filter": "item",
"values": [
"000000KL"
]
}
},
{
"code": "Tid",
"selection": {
"filter": "item",
"values": ["2011"]
}
}
],
"response": {
"format": "json"
}
}
And the response will be :
{
"columns": [
{
"code": "Tid",
"text": "year",
"type": "t"
},
{
"code": "000000KL",
"text": "Konsumentprisindex (KPI) fastställda årsmedeltal, totalt, 1980=100",
"type": "c"
}
],
"comments": [],
"data": [
{
"key": [
"2011"
],
"values": [
"311.43"
]
}
],
"metadata": [
{
"infofile": "PR0101",
"updated": "2021-01-13T12:50:00Z",
"label": "Konsumentprisindex (KPI) fastställda årsmedeltal, totalt, 1980=100 by year and observations",
"source": "Statistics Sweden"
}
]
}
And you can change the values to get the information of the year you need .

Nativescript-vue TabView unable to render first item coming from API

Situation:
Im working on nativescript-vue app where im using TabView Items to create tabs. The title for tab and the information inside the tab is being for looped from JSON data file.
Problem:
The first tabviewitem doesnt render any information. Inorder to see the data, i have to click on other tabs first go back to first tab. After that, i can see the items
The markup i have to create tab using nativescript-vue:
<TabView
android:tabBackgroundColor="#ffffff"
android:tabTextColor="#ffa801"
android:selectedTabTextColor="#f53b57"
androidSelectedTabHighlightColor="#ffffff"
androidTabsPosition="Bottom">
<TabViewItem v-for="subcategory in subcategories" :title="subcategory.name" >
<FlexboxLayout>
<Label :text="subcategory.name" />
</FlexboxLayout>
</TabViewItem>
</TabView>
Subcategories is JSON array coming from API with following structure.
[
{
"id": 3,
"category_id": 1,
"name": "Vegetarian",
"ar_name": null,
"description": "Vegetarian",
"ar_description": null,
"image": null,
"created_at": "2020-03-04 04:12:13",
"updated_at": "2020-03-04 04:12:13",
"items": [
{
"id": 6,
"subcategory_id": 3,
"name": "Salad",
"ar_name": null,
"description": "test",
"ar_description": null,
"price": "100",
"status": "1",
"ar_price": null,
"discount": null,
"discount_colour": null,
"created_at": "2020-05-07 05:32:17",
"updated_at": "2020-05-07 05:32:17"
}
]
},
{
"id": 2,
"category_id": 1,
"name": "Sea Food",
"ar_name": null,
"description": "sea food",
"ar_description": null,
"image": null,
"created_at": "2020-03-04 04:11:38",
"updated_at": "2020-03-04 04:11:38",
"items": [
{
"id": 4,
"subcategory_id": 2,
"name": "some item",
"ar_name": null,
"description": "desc",
"ar_description": null,
"price": "100",
"status": "1",
"ar_price": null,
"discount": null,
"discount_colour": null,
"created_at": "2020-05-06 12:02:58",
"updated_at": "2020-05-06 12:02:58"
}
]
}
]
Solutions that i have tried
https://github.com/nativescript-vue/nativescript-vue/issues/515
but no luck
[Update] here is my script:
<script >
import axios from 'axios';
import Login from "./Login";
import FoodItems from "./FoodItems"
import SubCategories from "./parts/SubCategories"
import CategoryButtons from "./parts/CategoryButtons"
import Popular from "./parts/Popular"
// import Items from "./Items"
export default {
components: {SubCategories, CategoryButtons, Popular},
props: ['parentCategory'],
data() {
return {
subcategories: [],
populars: [],
categories:this.$store.getters.getCategories,
}
},
mounted(){
axios({
method:"GET",
"url":this.$store.state.apiUrl+"categories/"+this.parentCategory.id+"/subcategories",
headers:{
'Accept': 'application/json',
'Authorization': 'Bearer ' + this.$store.getters.getToken,
}
}).then(
response =>
{
//
this.subcategories =response.data.fooditems;
this.populars = response.data.popularitems;
// console.log(response.data.popularitems);
}, error => {
console.error(error);
}
);
},
methods: {
checkToken() {
this.$store.commit("loadFromStorage");
if(!this.$store.getters.getToken) { this.$navigateTo(Login, { clearHistory: true }) }
},
goToShowCase(args) {
// console.log(args);
this.$navigateTo(Showcase,
{
props:
{ parentCategory: args }
});
}
}
}
</script>
Update 2:
I created a similar issue on nativescript playground.
https://play.nativescript.org/?template=play-vue&id=7mNLr7
Thank you in advance!
Does adding a :key to your iterated items solve the issue?
<TabViewItem v-for="subcategory in subcategories"
:key="some_unique_value_between_them"
:title="subcategory.name"
loaded="mainContentLoaded">

how to fetch data according id/slug in ReactJS?

what i am trying to do is fetching the data according to category id/slug. for e.g i have two categories(brown, black) as you can see below. how to fetch blog_set data according to category id/slug ?
i am probably new to ReactJs. it would be great if anyone could help me out what i am trying to do is. thank you so much in advance.
endpoint-url : http://localhost:8000/api/category
api-data:
[
{
"id": 1,
"title": "brown",
"slug": "brown",
"image": "http://localhost:8000/media/category/bg_1.jpg",
"description": "",
"created_on": "2020-05-08T15:21:02Z",
"status": true,
"blog_set": [
{
"id": 6,
"url": "http://localhost:8000/api/blog_detail/test3",
"title": "test3",
"slug": "test3",
"image": "http://localhost:8000/media/blog/author.jpg",
"description": "test3",
"created_on": "2020-05-13T13:36:45Z",
"status": true,
"category": [
1
]
}
]
},
{
"id": 2,
"title": "black",
"slug": "black",
"image": "http://localhost:8000/media/category/image_7.jpg",
"description": "",
"created_on": "2020-05-08T17:14:43Z",
"status": true,
"blog_set": [
{
"id": 10,
"url": "http://localhost:8000/api/blog_detail/test3",
"title": "Hamid",
"slug": "test3",
"image": "http://localhost:8000/media/blog/person_2_2beHkt1.jpg",
"description": "test",
"created_on": "2020-05-13T14:59:30.855849Z",
"status": true,
"category": [
2
]
}
]
}
]
./src/Category.js
export default class App extends Component{
state = {
bloglist: [],
};
componentDidMount() {
this.fetchData();
}
fetchData = async () => {
try {
const response = await fetch("http://localhost:8000/api/category");
const jsonResponse = await response.json();
this.setState({ bloglist: jsonResponse });
} catch (error) {
console.log(error);
}
};
render(){
{
const { bloglist } = this.state;
if (!bloglist) {
return (
<div>
<h1>loading...</h1>
</div>
);
}
return(
<div>
<h1>Category</h1>
{bloglist.map((bloglist) => (
<div>
<div class="col-md-12">
<div class="blog-entry animate d-md-flex">
<img src={bloglist.image} className="App-logo"/>
<h3 class="mb-2">{bloglist.title}</h3>
<h3 class="mb-2">{bloglist.blog_set.title}</h3>
</div>
</div>
</div>
))}
</div>
);
}
}
}
First check if the api supports fetching single category with id/slug. Then if you can call API with the id/slug from added to the fetch API call. If you want to show a separate page with the selected category you can enable a route with URL parameter with react-router-dom (https://reacttraining.com/react-router/web/example/url-params). And with this you will get the id/slug in the match prop which will be the this.props.history.match or with useParams() hooks. and then you can use it to call API with the selected id/slug.
Your UI URL will look like this. http://localhost:3000/category/:id and on browser it will look like this http://localhost:3000/category/black so when you call useParams() hook in your component it will be like {id} = useParams();
Now you can use this id to call the single selection API which might look like this <api_url>:<port>/category/black or <api_url>:<port>/category?slug=black
Pass query-params access deep properties
GET http://localhost:8000/api/category?slug=value
fetchData = async () => {
try {
const response = await fetch("http://localhost:8000/api/category?slug=value");
const jsonResponse = await response.json();
this.setState({ bloglist: jsonResponse });
} catch (error) {
console.log(error);
}
};

Categories