Display data from object in Strapi - javascript

When I write {{ posts }} I see this object but when I want to display it in a v-for, it doesn't show up.
This is what I have by using {{ posts }}
{
"data": [
{
"id": 1,
"attributes": {
"title": "Post numer jeden",
"content": "tresc w poscie numer jeden",
"createdAt": "2022-10-27T17:51:40.396Z",
"updatedAt": "2022-10-27T17:51:44.406Z",
"publishedAt": "2022-10-27T17:51:44.405Z"
}
},
{
"id": 2,
"attributes": {
"title": "Post numer dwa",
"content": "Tresc w poscie numer dwa",
"createdAt": "2022-10-27T17:52:06.344Z",
"updatedAt": "2022-10-27T17:52:07.669Z",
"publishedAt": "2022-10-27T17:52:07.668Z"
}
}
],
"meta": {
"pagination": {
"page": 1,
"pageSize": 25,
"pageCount": 1,
"total": 2
}
}
}
<template>
<p>{{ posts }}</p>
<div v-for="post in posts" :key="post">
<hr />
<h3>{{ post.title }}</h3>
<p>dsdsa</p>
</div>
</template>
<script>
import axios from "axios";
export default {
data() {
return {
posts: [],
};
},
async created() {
const res = await axios.get("http://localhost:1337/api/posts");
this.posts = res.data;
},
};
</script>

This is a common issue, solved by going one level down.
Try the following
<div v-for="post in posts.data" :key="post.id">

Related

how to display list of orders from my database in vue js

i've successfully updated my orders after payment please how can i display it in my vue front end
this is my html template which shows the list of orders made
<template>
<div>
<div
v-for="order in orders"
:key="order._id"
>
<div
v-for="product in order.products"
:key="product._id"
>
{{ product.productID.title }}
</div>
</div>
</div>
</template>
this is my script tag
<script>
import { mapActions } from "vuex";
import { mapGetters } from "vuex";
import axios from "axios";
export default {
name: "Products",
data() {
return {
orders: [],
name: "",
email: ""
};
},
created() {
//user is not authorized
if (localStorage.getItem("token") === null) {
this.$router.push("/login");
}
},
mounted() {
const token = localStorage.getItem("token");
axios
.get("http://localhost:5000/api/orders", {
headers: {
Authorization: "Bearer" + token,
"x-access-token": token
}
})
.then(res => {
console.log(res);
orders: res.products;
});
axios
.get("http://localhost:5000/api/auth/user", {
headers: {
Authorization: "Bearer" + token,
"x-access-token": token
}
})
.then(res => {
console.log(res);
this.name = res.data.user.name;
this.email = res.data.user.email;
})
.catch(error => {
console.log(error);
});
}
};
</script>
this the json object i get in my console
[
{
"_id": "62d163b638cbafee24c6d663",
"products": [
{
"productID": {
"_id": "625672a8370e769a8a93a51e",
"reviews": [],
"owner": {
"_id": "6220db7ee861f3dbbaf21e3d",
"name": "mr jacob",
"about": "hello",
"__v": 0
},
"category": "62566ec30e42d6c5ab370e7c",
"title": "galaxy note",
"description": "Lorem ipsum dolor sit amet, ",
"photo": "https://aji.s3.eu-west-2.amazonaws.com/1649832580792",
"price": 300,
"stockQuantity": 1,
"__v": 0,
"id": "625672a8370e769a8a93a51e"
},
"quantity": 1,
"price": 300,
"_id": "62d163b638cbafee24c6d664"
}
],
"owner": {
"_id": "6278e8bc1966b7d3783ced8e",
"name": "bas",
"email": "bas#gmail.com",
"password": "$2a$10$3QkbA805Pn/QBYMd6sULi.FGjETYoMf44wuV1mtOZahhPzm5zeL4G",
"__v": 0,
"address": "62b2cfd8d0846785cd87c64d"
},
"estimatedDelivery": "",
"__v": 0
}
]
i'm not getting any error in my console so i don't seem to know where the problem is
Your code looks fine to me and it is working fine. One small observation, As per the console data you posted, It should be this.orders = res instead of orders = res.products.
Live Demo :
new Vue({
el: '#app',
data: {
orders: []
},
mounted() {
const apiResponse = [
{
"_id": "62d163b638cbafee24c6d663",
"products": [
{
"productID": {
"_id": "625672a8370e769a8a93a51e",
"reviews": [],
"owner": {
"_id": "6220db7ee861f3dbbaf21e3d",
"name": "mr jacob",
"about": "hello",
"__v": 0
},
"category": "62566ec30e42d6c5ab370e7c",
"title": "galaxy note",
"description": "Lorem ipsum dolor sit amet, ",
"photo": "https://aji.s3.eu-west-2.amazonaws.com/1649832580792",
"price": 300,
"stockQuantity": 1,
"__v": 0,
"id": "625672a8370e769a8a93a51e"
},
"quantity": 1,
"price": 300,
"_id": "62d163b638cbafee24c6d664"
}
],
"owner": {
"_id": "6278e8bc1966b7d3783ced8e",
"name": "bas",
"email": "bas#gmail.com",
"password": "$2a$10$3QkbA805Pn/QBYMd6sULi.FGjETYoMf44wuV1mtOZahhPzm5zeL4G",
"__v": 0,
"address": "62b2cfd8d0846785cd87c64d"
},
"estimatedDelivery": "",
"__v": 0
}
];
this.orders = apiResponse;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<div
v-for="order in orders"
:key="order._id"
>
<div
v-for="product in order.products"
:key="product._id"
>
{{ product.productID.title }}
</div>
</div>
</div>
this.orders = res.data.products was what solved my problem

Vue.js 3 and search

I have a data coming from API. It is an array of "houses".
Code looks like this:
<template>
<div class="search__sort">
<input v-model="search" placeholder="Search for a house">
<button class="sort__button">Price</button>
<button class="sort__button">Size</button>
</div>
<div v-for="house in houses" :key="house.id" class="house">
<router-link :to="{ name: 'HouseDetails', params: { id: house.id}}" >
<h2>ID = {{ house }}</h2>
<h3> {{ house.location.street}} </h3>
<img :src="house.image" />
</router-link>
<button v-if="house.madeByMe" class="delete" #click="deleteHouse(house.id)">Delete</button>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'Houses',
data(){
return {
houses: [],
}
},
created() {
this.getHouses();
},
methods: {
getHouses(){
// GET request using axios with set headers
const headers = { "CENSORED": "CENSORED" };
axios.get('myAPI', { headers })
.then(response => this.houses = response.data);
},
deleteHouse(id) {
const headers = { "CENSORED": "CENSORED" };
axios.delete('myAPI' + id, { headers })
.then(response => {
console.log(response);
})
.catch(function (error) {
console.log(error.response);
});
},
},
}
</script>
I somehow need to implement the filter by text input, so that for example, if user types a city name it will show all of those houses or a street name to filter that by street.
Any suggestions how I can do that with code that I already have?
You can use computed property:
new Vue({
el: '#demo',
data() {
return {
search: '',
houses: [{ "id": 2, "image": "myAPI/house1.jpg", "price": 123, "rooms": { "bedrooms": 1, "bathrooms": 1 }, "size": 500, "description": "oui", "location": { "street": "street 20", "city": "assas", "zip": "asasdd" }, "createdAt": "2020-05-07", "constructionYear": 2000, "hasGarage": false, "madeByMe": false }, { "id": 3, "image": "myAPI/house1.jpg", "price": 123, "rooms": { "bedrooms": 1, "bathrooms": 1 }, "size": 500, "description": "oui", "location": { "street": "street 20", "city": "adb", "zip": "asasdd" }, "createdAt": "2020-05-07", "constructionYear": 2000, "hasGarage": false, "madeByMe": false },{ "id": 4, "image": "myAPI/house1.jpg", "price": 123, "rooms": { "bedrooms": 1, "bathrooms": 1 }, "size": 500, "description": "oui", "location": { "street": "street 20", "city": "bbb", "zip": "asasdd" }, "createdAt": "2020-05-07", "constructionYear": 2000, "hasGarage": false, "madeByMe": false }],
}
},
computed: {
filteredHouses(){
return this.houses.filter(h => h.location.city.toLowerCase().includes(this.search.toLowerCase()))
}
}
})
Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
<div class="search__sort">
<input v-model="search" placeholder="Search for a house">
<button class="sort__button">Price</button>
<button class="sort__button">Size</button>
</div>
<div v-for="house in filteredHouses" :key="house.id" class="house">
<h3> {{ house.location.city}} </h3>
<img :src="house.image" />
</div>
</div>
You will want to distinguish the difference between houses and displayedHouses such that, displayedHouses is your filtered array.
<h2>ID = {{ house }}</h2> is not going to play well with your testing
displayedHouses will be a computed looking something like:
computed:
{
/**
* #return {array} List of displayed houses from search input
*/
displayedHouses()
{
if (!this.houses || !this.houses.length)
{
return []
}
if (!this.search)
{
return this.houses
}
return this.houses.filter( (house) =>
{
return house.city.includes(this.search) || house.state.includes(this.search) // || whatever else you want
})
}
},

VusJs: Error in render: "Type Error: Cannot read property 'data' of undefined"

enter image description here
i request data from API and data was succesfuly, but i get this error
<template>
<!-- <h1>{{ hasil }}</h1> -->
<div>
<div v-for=" h in hasil.data.data " :key="h.id">
<div class="card blue-grey darken-1 left-align">
<div class="card-content white-text">
<span class="card-title">Title: {{ h.title }} | ID: {{ h.id }}</span>
<p>Body: {{ h.body }}</p>
</div>
<div class="card-action">
This is a link
This is a link
</div>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'ListArticle',
data () {
return {
hasil: []
}
},
created () {
axios.get('http://xxx.xxxxx.com/api/laravel')
.then(response => (this.hasil = response))
}
}
</script>
here the value
{
"current_page": 1,
"data": [
{
"id": 10,
"user_id": 1,
"category_posts_id": 1,
"title": "jjjjj kkkkk",
"body": "jjjjj kkkkkkkkkkkkkkk",
"slug": "jjjjj-kkkkk",
"active": 1,
"file_name": "phpheEduN.PNG",
"original_file_name": "Capture.PNG",
"file_path": "storage/app/public",
"created_at": "2018-05-01 13:00:13",
"updated_at": "2018-05-01 13:00:13",
"url": "xxx"
},
{
"id": 9,
"user_id": 1,
"category_posts_id": 1,
"title": "asaaaaaaa jhabsd",
"body": "aaa kjjkj",
"slug": "xxx",
"active": 1,
"file_name": "phpcUz7qV.PNG",
"original_file_name": "Capture.PNG",
"file_path": "storage/app/public",
"created_at": "2018-05-01 12:38:46",
"updated_at": "2018-05-01 12:38:46",
"url": ""
},
{
"id": 8,
"user_id": 1,
"category_posts_id": 1,
"title": "hkbakjbcscsdcsd",
"body": "alsdjnblsjdccsdsfsdfdsffsfs",
"slug": "hkbakjbcscsdcsd",
"active": 1,
"file_name": "php1LDUPr.PNG",
"original_file_name": "Capture.PNG",
"file_path": "storage/app/public",
"created_at": "2018-05-01 12:33:46",
"updated_at": "2018-05-01 12:33:46",
"url": ""
},
{
"id": 1,
"user_id": 1,
"category_posts_id": 1,
"title": "test title",
"body": "test body",
"slug": "test-title",
"active": 1,
"file_name": "",
"original_file_name": "",
"file_path": "",
"created_at": null,
"updated_at": null,
"url": ""
}
],
"first_page_url": "xxx",
"from": 1,
"last_page": 1,
"last_page_url": "xxx",
"next_page_url": null,
"path": "xxx",
"per_page": 5,
"prev_page_url": null,
"to": 4,
"total": 4
}
vue can't resolve data when vnode created,you can modify your code like this:
export default {
name: 'ListArticle',
data () {
return {
hasil: {data:{data:[]}}
}
},
created () {
axios.get('http://xxx.xxxxx.com/api/laravel')
.then(response => (this.hasil = response))
}
}
or like this:
<template>
<!-- <h1>{{ hasil }}</h1> -->
<div>
<div v-for=" h in hasil.data " :key="h.id">
<div class="card blue-grey darken-1 left-align">
<div class="card-content white-text">
<span class="card-title">Title: {{ h.title }} | ID: {{ h.id }}</span>
<p>Body: {{ h.body }}</p>
</div>
<div class="card-action">
This is a link
This is a link
</div>
</div>
</div>
</div>
</template>
export default {
name: 'ListArticle',
data () {
return {
hasil: {data:[]}
}
},
created () {
axios.get('http://xxx.xxxxx.com/api/laravel')
.then(response => (this.hasil = response.data))
}
}
The reason why you're getting the error Type Error: Cannot read property 'data' of undefined is because you're trying to accessthis when the arrow notation function in the axios request changes the this reference. You'd actually want to do something like this instead:
import axios from 'axios'
export default {
name: 'ListArticle',
data () {
return {
hasil: []
}
},
created () {
// Create reference to this so you can access the Vue
// reference inside arrow notation functions
var self = this;
axios.get('http://xxx.xxxxx.com/api/laravel')
.then(response => (self.hasil = response))
}
}

Retrieve a value from json array response in angular 4

I'm able to get all users with their roles from the backend laravel.
This is the response.
{
"users": [
{
"id": 2,
"first_name": "user",
"last_name": "xyz",
"title": null,
"email": "user#gmail.com",
"phone_number": "***-***-****",
"phone_type": "home",
"inactive": 0,
"created_at": null,
"updated_at": null,
"is_verified": 0,
"roles": [
{
"id": 1,
"name": "Account User",
"pivot": {
"user_id": 2,
"role_id": 1
}
}
]
},
I'm retrieving the users data like this
in ts:
ngOnInit() {
this.http.get<User>('backend.url')
.subscribe(data => {
this.user = data;
console.log(data);
});
}
in html:
<tr *ngFor="let userData of user?.users; trackBy: userThumb">
<td>{{ userData?.first_name }}</td>
Now, I want to show the role name of the user in a frontend table.
How do I retrieve the roles->name in angular 4 from this users array?
look this:
<tr *ngFor="let userData of user?.users; trackBy: userThumb">
<td *ngFor="let role of userData ?.roles; > {{role ?.name}}</td>
</tr>

Angular display nested json value

Here is my data:
{
"statusCode": 200,
"result": {
"items": [
{
"Name": "date",
"Fields": {
"{3C3170EE-E6D5-4075-A864-8AB86D1E8E98}": {
"Name": "Promo Content",
"Value": "September 22, 2015"
}
}
},
{
"Name": "rate",
"Fields": {
"{3C3170EE-E6D5-4075-A864-8AB86D1E8E98}": {
"Name": "Promo Content",
"Value": "10%"
}
}
},
{
"Name": "description",
"Fields": {
"{3C3170EE-E6D5-4075-A864-8AB86D1E8E98}": {
"Name": "Promo Content",
"Value": "This rate is good as of the date listed above."
}
}
}
]
}
}
And here is my HTML and JS:
<body ng-app="myApp">
<div ng-controller="CallWebApi">
<ul>
<li ng-repeat="items in data">
{{ items.Name }}: {{ items.Fields }}
</li>
</ul>
</div>
<script>
angular.module('myApp',[]).controller('CallWebApi', function($scope, $http) {
// Local version of the data
$http.get('./test.js').
success(function (data) {
$scope.data = data.result.items;
console.log('success ' + data)
})
.error(function(data) {
console.log('failure ' + data)
});
});
</script>
</body>
My question is, how do I display the Value field nested in the Fields field?
I'm expecting:
date: September 22, 2015
rate: 10%
description: This rate is good as of the date listed above.
<ul>
<li ng-repeat="item in data">
{{ item.Name }}: {{ item.Fields["{3C3170EE-E6D5-4075-A864-8AB86D1E8E98}"].Value }}
</li>
</ul>

Categories