how to fetch only specific data from graphql query - javascript

I am trying to fetch some data from my CMS but I am facinf an error when fetching a specific data.
It's an array that I want to fetch with the graphql query :
{
allPrismicLastPosts {
nodes {
data {
links {
blog {
document {
... on PrismicBlog {
data {
post_img {
url
}
post_title {
text
}
post_paragraph {
text
}
tag
}
}
... on PrismicCulture {
data {
tag
culture_image {
url
}
culture_paragraph {
text
}
culture_title {
text
}
}
}
}
}
}
}
}
}
}
This is it JSON Format :
"links": [
{
"blog": {
"document": {
"data": {
"post_img": {
"url": "https://images.prismic.io/zinee/67254822-5c44-42fe-8d5b-7f500141c3a7_Mask%20Group%20(1).png?ixlib=gatsbyFP&auto=compress%2Cformat&fit=max"
},
"post_title": {
"text": "Make more time for the work that matters most using our services"
},
"post_paragraph": {
"text": "A lot of different components that will help you create the perfect look"
},
"tag": "Fiction"
}
}
}
},
{
"blog": {
"document": {
"data": {
"post_img": {
"url": "https://images.prismic.io/zinee/4898e2a8-ebfb-41d4-b843-550e9d9c84da_Mask%20Group.png?ixlib=gatsbyFP&auto=compress%2Cformat&fit=max"
},
"post_title": {
"text": "Make myspace your best designed space"
},
"post_paragraph": {
"text": "A lot of different components that will help you create the perfect look"
},
"tag": "Fiction"
}
}
}
},
{
"blog": {
"document": {
"data": {
"post_img": {
"url": "https://images.prismic.io/zinee/67254822-5c44-42fe-8d5b-7f500141c3a7_Mask%20Group%20(1).png?ixlib=gatsbyFP&auto=compress%2Cformat&fit=max"
},
"post_title": {
"text": "Make more time for the work that matters most using our services"
},
"post_paragraph": {
"text": "A lot of different components that will help you create the perfect look"
},
"tag": "Fiction"
}
}
}
},
{
"blog": {
"document": {
"data": {
"post_img": {
"url": "https://images.prismic.io/zinee/4898e2a8-ebfb-41d4-b843-550e9d9c84da_Mask%20Group.png?ixlib=gatsbyFP&auto=compress%2Cformat&fit=max"
},
"post_title": {
"text": "Make myspace your best designed space"
},
"post_paragraph": {
"text": "A lot of different components that will help you create the perfect look"
},
"tag": "Fiction"
}
}
}
}
]
I get a Cannot read properties of undefined (reading 'text') error when I fetch it like this :
{post.data.links.map((test)=>
(
<>
<h1>{test.blog.document.data.post_paragraph.text}</h1>
</>
))}
But when I try to fetch like this it works:
{post.data.links.map((test)=>
(
<>
<h1>{test.blog.document.data.tag}</h1>
</>
))}
Any idea how to fix this please ?
the tag field works and get fetched perfectly but with data like : post_paragraph.text or title.text doesn't work !!

Your GraphQL fragment PrismicBlog has post_paragraph which has text (so your loop works) however, when it's mapping PrismicCulture fragment, where the structure differs, your map breaks because there's no such property, in PrismicCulture it's called culture_paragraph with a text property in it.
If you are trying to map both fragments in one loop I'd suggest using the same data structure in the CMS, changing culture_paragraph for post_paragraph so your loop will be valid.
If that's not an option, you can use GraphQL alias to map your culture_paragraph into post_paragraph such as:
{
allPrismicLastPosts {
nodes {
data {
links {
blog {
document {
... on PrismicBlog {
data {
post_img {
url
}
post_title {
text
}
post_paragraph {
text
}
tag
}
}
... on PrismicCulture {
data {
tag
culture_image {
url
}
post_paragraph: culture_paragraph {
text
}
culture_title {
text
}
}
}
}
}
}
}
}
}
}
Note the post_paragraph: culture_paragraph alias.
Another alternative is using the optional chaining to only print the text if the structure matches the loop:
{post.data.links.map((test)=>
(
<>
<h1>{test.blog.document?.data?.post_paragraph?.text}</h1>
</>
))}

Related

How to query a specific node using Graphql?

I am trying to use Graphql to return a specific instance of an object.
This is my Graphql query:
query MyQuery {
allContentfulFlexStyleBody {
edges {
node {
image {
file {
url
}
}
}
}
}
}
It returns 3 Nodes:
{
"data": {
"allContentfulFlexStyleBody": {
"edges": [
{
"node": {
"image": {
"file": {
"url": "//images.ctfassets.net/m7ipc0qjqa17/6JTBUN3mkENLvEVuC/6ff4b2da441f1c7cec2eb401534aa749/-19.jpeg"
}
}
}
},
{
"node": {
"image": {
"file": {
"url": "//images.ctfassets.net/m7ipc0qjqa17/2s6lg5oBJ7F780DI1/b4068dcc9cc889dbcd09ed992793e771/-BTS.png"
}
}
}
},
{
"node": {
"image": {
"file": {
"url": "//images.ctfassets.net/m7ipc0qjqa17/6bRRjlI1nLFCdUawZ/12af617d352b21864192dcc033198951/MyStylist_Photo_Grid_Layout__Retouched_Photos_Shortlist-6.jpeg"
}
}
}
}
]
}
},
"extensions": {}
}
I am attempting to display one image within my gatsby project as such:
{data.allContentfulFlexStyleBody.edges.map(({ node }, index) => (
<img
className={"contentFeatureImg"}
alt={``}
key={``}
src={node.image.file.url}
/>
))}
All images are being displayed. How do I access the first, second or third node exclusively without returning the entire edges array?
Accessing a specific element of the edges array works enough for what I'm doing here:
<img
className={"contentFeatureImg1"}
alt={``}
key={``}
src={data.allContentfulFlexStyleBody.edges[0].node.image.file.url}
/>

unable to push multiple values/ data to the angular 2-tree

i am having a dynamic json data & 3 buttons "feed data" it contains one set of dynamic data and button 2 " feed another data" it contains another set of dynamic data and button 3 is " Send data" here my issue when ever i press feed data and select option and press send data it is working and after that if i press feed another data and press send data then it is giving error"isSelected is undefined"
error simulation : feed data --> select option --> send data & press feed another data --> select options --> send data then we are getting error
options = {
useCheckbox: true
};
arrayData;
nodes;
data = {
"info": {
"laptop": {
},
"config": {
"properties": {
"ram": {
},
"processor": {
},
"hdd": {
}
}
},
"link": {
},
"name": {
},
"company": {
"properties": {
"model": {
},
"maker": {
"type": "integer"
},
"country": {
"type": "text"
},
"enterprise": {
}
}
}
}
};
dataa = {
"info": {
"mobile": {
},
"config": {
"properties": {
"ram": {
},
"processor": {
},
"storage": {
}
}
},
"link": {
},
"name": {
},
"company": {
"properties": {
"model": {
},
"maker": {
"type": "integer"
},
"country": {
"type": "text"
},
"enterprise": {
}
}
}
}
};
click(tree:TreeModel)
{
this.arrayData= [];
console.log(tree.activeNodes);
let result: any = {};
let rs = [];
// tree.selectedLeafNodeIds = {};
Object.keys(tree.selectedLeafNodeIds).forEach(x=>{
let node:TreeNode=tree.getNodeById(x);
if (node.isSelected)
{
if (node.parent.data.name) //if the node has parent
{
rs.push(node.parent.data.name+'.'+node.data.name);
if (!result[node.parent.data.name]) //If the parent is not in the object
result[node.parent.data.name] = {} //create
result[node.parent.data.name][node.data.name] = true;
}
else {
if (!result[node.data.name]) //If the node is not in the object
result[node.data.name] = {} //create
rs.push(node.data.name);
}
}
})
this.arrayData = rs;
}
feedData(){
const results = Object.keys(this.data.info).map(k => ({
name: k,
children: this.data.info[k].properties
? Object.keys(this.data.info[k].properties).map(kk => ({name: kk}))
: []
}));
this.nodes = results;
}
feedAnother(){
const results = Object.keys(this.dataa.info).map(k => ({
name: k,
children: this.dataa.info[k].properties
? Object.keys(this.dataa.info[k].properties).map(kk => ({name: kk}))
: []
}));
this.nodes = results;
}
when ever i press feed data and press send data then i am able to view the info and lie wise i want to update data i press feed another data then press send data then it needs to get the updated results
below is my stack blitz url : https://stackblitz.com/edit/angular-zapxko
You can simply change nodes object to update the result.
You need to use Async Data method to update nodes. Here are the demo and code from Angular Tree's official documentation.

How to get the value of a deep nested json object?

I'm working on an app in javascript, and I have this json object (this is a simplified example of the actual json object)
{
"data": [
"user": {
"pictures"{
"sizes"[
0: {
"link": "http://www"
},
1: {
"link": "http://"
}
]
}
}
]
}
And I want to get the value of link, so i tried data.user.pictures.sizes[0].link, and it returned an error. How to get the right value?
edit: I'm using a map function to loop around the data object, so i can display values in an html page. it works for most of the other items, except for pictures sizes, i cant seem to get the value of the second item in the sizes array.
From the data, it shows that 'data' contains array and sizes contains array that contains object of properties 0 and 1 , so do this
data[0].user.pictures.sizes[0].0.link
First of all you need to have colons to "pictures" and "sizes" :)
Secondly, it depends what your structure is.
for example:
if you need to use arrays as they appear in your example:
var a = {
"data": [
{
"user": {
"pictures": {
"sizes": [
{
0: {
"link": "http://www"
}
},
{
1: {
"link": "http://"
}
}
]
}
}
}
]
}
console.log(a.data[0].user.pictures.sizes[0][0].link);
or you just need a json without arrays in it:
var b = {
"data": {
"user": {
"pictures": {
"sizes": {
0: {
"link": "http://www"
},
1: {
"link": "http://"
}
}
}
}
}
}
console.log(b.data.user.pictures.sizes[0].link);
or you can even mix them:
var c = {
"data": {
"user": {
"pictures": {
"sizes": [
{
"link": "http://www"
},
{
"link": "http://"
}
]
}
}
}
}
console.log(c.data.user.pictures.sizes[0].link);
notice the subtle difference of "sizes" in b and c and the double array of a. This is because json with index as keys is the same as an array. check this example:
var example = [
{
0: "example00",
1: "example01",
2: "example02"
},
{
0: "example10",
1: "example11",
2: "example12"
},
]
console.log(example[0][1]); // == example01
you can see that you have 2 arrays within the example array
hope that helps :)
Your JSON is wrong, it should be as below :
var js = {
"data": {
"user":{
"pictures":{
"sizes":[
{
"link":"http://www"
},
{
"link":"http://"
}
]
}
}
}
}
To get the value:
js.data.user.pictures.sizes[0].link

How to print normalized data in React/Redux

I have a data normalized using normalizr:
{
result: "123",
entities: {
"articles": {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: [ "324" ]
}
},
"users": {
"1": { "id": "1", "name": "Paul" },
"2": { "id": "2", "name": "Nicole" }
},
"comments": {
"324": { id: "324", "commenter": "2" }
}
}
}
I save entities in reducer and I want to print them on my page.
I can do that like this:
const articles = data.entities.articles;
for (let key in articles) {
console.log( articles[key].author + ', ' + articles[key].title);
}
Is that ok in React/Redux print normalized data in JSX template like this or there is exist a better way?
UPD
I create an application using this example https://github.com/reactjs/redux/tree/master/examples/real-world but I don't understand how there a data from entities printed in JSX templates.
I am confused about a data structure because usually I used arrays but in real-world example a new for me way, where data normalized like this.
To connect your reducer with your view, you need a container. Then in your view, you can do something like in following jsfiddle.
https://jsfiddle.net/madura/g50ocwh2/
var data = {
result: "123",
entities: {
"articles": {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: ["324"]
}
},
"users": {
"1": {
"id": "1",
"name": "Paul"
},
"2": {
"id": "2",
"name": "Nicole"
}
},
"comments": {
"324": {
id: "324",
"commenter": "2"
}
}
}
};
console.log(data.entities.articles);
return ( < div > {
Object.keys(data.entities.articles).map(function(key) {
return <p key = {
key
} > {
data.entities.articles[key].title
} < /p>
})
} < /div>);
}
You will get your data as a property to your view after you connect with container. So you can access your data like below in your view.
this.props.data.entities.articles;

(Handlebarsjs templating) How to get data from external JSON source?

See this link: http://jsfiddle.net/Rousnay/FJzre/ it is working, the JSON data come trough http://json.virtuecenter.com/json-data/blogs/tags?callback=?
but it is not working when i want to get data from http://sunday-theater-club.simpletix.eu/API/ThemeUIHandler.asmx/GetMenuItems?callback=?
Can anyone help me with jsfiddle example. please.
The returned data is not valid to the template, when getting from "http://sunday-theater-club.simpletix.eu/API/ThemeUIHandler.asmx/GetMenuItems?callback=?" you end up with:
[
{
"text": "Home ",
"url": "/Default.aspx"
},
{
"text": "Events ",
"url": "/Event-List/"
},
{
"text": "Test",
"url": "/Pages/8276/Test/"
}
]
and when getting from "http://json.virtuecenter.com/json-data/blogs/tags?callback=?" you have:
{
"blogsTags": [
{
"tag":"GovernorBentley",
"count":1,
"separation_path":"\/blogs\/byTag\/GovernorBentley.html"
},
{
"tag":"Huntsville",
"count":1,
"separation_path":"\/blogs\/byTag\/Huntsville.html"
},
{
"tag":"Voting Responsibility",
"count":1,
"separation_path":"\/blogs\/byTag\/Voting Responsibility.html"
},
{
"tag":"Voting Rights",
"count":1,
"separation_path":"\/blogs\/byTag\/Voting Rights.html"
}
],
"pagination": {
"limit":20,
"total":4,
"page":1,
"pageCount":1
}
}
your template expects a "blogsTags" property.

Categories

Resources