I am trying to map through the following data and return "Balance" but it keeps telling me that "coding" its undefined.
here its the array
"entry": [
{
"resource": {
"id": "1980438",
"type": {
"coding": [
{
"system": "https://www.medeo-health.com/uploads/1/1/8/1/118121028/s491564155970805143-c3-i1-w640_orig.jpeg",
"code": "25062444",
"display": "Balance"
}
]
},
"manufactureDate": "2017-01-08",
"expirationDate": "2020-01-08",
"owner": {
"reference": "Organization/1980437"
}
},
"search": {
"mode": "match"
}
}, ...
this is what I am trying:
import React, { Component } from 'react';
import Device from './Device/Device';
import axios from 'axios';
class Devices extends Component {
state = {
devices: null
}
componentDidMount() {
axios.get('http://hapi.fhir.org/baseDstu3/Device?organization=1980437&_include=Device:organization&_sort=device-name')
.then(res => {
this.setState({ devices: res.data.entry });
})
.catch(error => {
console.log(error);
})
}
render() {
let devices = <p style={{ textAlign: "left", margin: "0" }}>This practitioner have no devices!</p>;
if (this.state.devices) {
devices = this.state.devices.map(device => {
return (
<Device
key={device.resource.id}
name={device.resource.type.coding[0].display}
/>
)
});
}
return (
<div>
{devices}
</div>
);
};
};
export default Devices;
the id returns well but for name it keeps getting "Cannot read property 'coding' of undefined"
what I am doing wrong?
Got the Issue. You are getting undefined because the last object you are receiving does not contain a type property in it. Please Check
Try Something Like this
{this.state.devices.map(device => {
if (device.resource.type) { //check type property exists first then render
console.log(device.resource.type.coding[0].display);
return (
<p key={device.resource.id}>
{device.resource.type.coding[0].display}
</p>
);
} else return null;
})}
Related
Hello everyone I have function like that.When I tried to call my datas I can just reach to first index of each array.For example I have 5 different pictures of playstation but on my web page I just see 1 picture. How can I fix it?Is something missing in function or should change to function ?
in advance thank you
import React from 'react'
import { gql, useQuery } from '#apollo/client';
import { Image } from 'antd';
import { useState } from 'react';
const GET_TECH = gql`
query AllItem{
categories{
name
products{
name
brand
attributes{
name
id
}
gallery
category
prices{
currency{
label
symbol
}
amount
}
inStock
description
}
}
}
`;
function Tech() {
const { loading, error, data } = useQuery(GET_TECH);
if (loading) return 'Loading...';
if (error) return `Error! ${error.message}`;
console.log(data);
return (
<div className='pageLayout'>
{
(data.categories).map((item,index) => {
//const {name,brand,description,gallery,category} = item;
{
return (item.products).map((itemPrdct,subIndex) => {
const {name,brand,description,gallery,category} = itemPrdct;
if(category === "tech"){
console.log(name)
return(
<div className="tech" key = {subIndex}>
<p className='nametag' >{brand}</p>
<Image width={200} src={gallery} className='gallery'/>
</div>
)
}
})
}
})
}
</div>
)
}
export default Tech
> //Graphql structure
{
"data": {
"categories": [
{
"name": "all",
"products": [
{
"name": "Nike Air Huarache Le",
"brand": "Nike x Stussy",
"attributes": [
{
"name": "Size",
"id": "Size"
}
],
"gallery": [
"https://cdn.shopify.com/s/files/1/0087/6193/3920/products/DD1381200_DEOA_2_720x.jpg?v=1612816087",
"https://cdn.shopify.com/s/files/1/0087/6193/3920/products/DD1381200_DEOA_1_720x.jpg?v=1612816087",
"https://cdn.shopify.com/s/files/1/0087/6193/3920/products/DD1381200_DEOA_3_720x.jpg?v=1612816087",
"https://cdn.shopify.com/s/files/1/0087/6193/3920/products/DD1381200_DEOA_5_720x.jpg?v=1612816087",
"https://cdn.shopify.com/s/files/1/0087/6193/3920/products/DD1381200_DEOA_4_720x.jpg?v=1612816087"
],
console.log
I was thinking if gallery is an array then it should use map on arrays
const {name,brand,description,gallery,category} = itemPrdct;
if(category === "tech"){
console.log(name)
return(
<div className="tech" key = {subIndex}> // key can be `${idx}${subIndex}` if products are repeating
<p className='nametag' >{brand}</p>
gallery?.map((url, idx) => {
return (<Image key={idx} width={200} src={url} className='gallery'/>)
}
</div>
)
} // else { return (<EmptyElement /> } // consider returning empty element
})
// map through the image
gallery?.map((url, idx) => {
return (<Image key={idx} width={200} src={url} className='gallery'/>)
}
you can use useMemo to transform the response and filter out empty elements then map the items as needed
hope it works
I have a JSON file:
[
{
"id": 1,
"availability": false
},
{
"id": 2,
"availability": true
}
]
What I would like to achieve is to automatically display an image of a tick if availability : true and to display an image of a cross if availability : false.
For example these are the names of the two images:
tick.jpg
cross.jpg
This is my code so far:
import React, { Component } from "react";
import "./styles.css";
class GetOnlinePosts extends Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
posts: []
};
}
componentDidMount() {
fetch("https://api.myjson.com")
.then(response => response.json())
.then(
result => {
this.setState({
isLoaded: true,
posts: result
});
},
error => {
this.setState({
isLoaded: true,
error
});
}
);
}
render() {
const { error, isLoaded, posts } = this.state;
const orderedPosts = [
...posts.filter(post => post.availability),
...posts.filter(post => !post.availability)
];
if (error) {
return <div>Error in loading</div>;
} else if (!isLoaded) {
return <div>Loading ...</div>;
} else {
return (
<div>
<div className="tiles">
{orderedPosts.map(post => (
<div key={post.id}>
<div className="tile"></div>
</div>
))}
</div>
</div>
);
}
}
}
export default GetOnlinePosts;
Unfortunately I am unable to have the images included in the with JSON. I would like the images to be within the <div className="tile"> </div> so any help on how to do this would be great. Thanks in advance.
<img src={post.availability ? 'tick.jpg' : 'cross.jpg'} />
I am trying to loop through a response from a data file however, I am getting an error I can't debug or see why it doesn't work. I had tried the forEach and map within a function but it failed just the same.
I had tried the forEach and map within a function but it failed just the same.
class GetTiles extends Component {
constructor(props) {
super(props);
this.state = {
tileData: {},
dataLoaded: false
};
}
loadData() {
axios("assets/data/home.json")
.then(response => {
this.setState({
tileData: response.data.titles,
dataLoaded: true
});
console.log("Local Tiles Ajax Call: Success");
})
.catch(err => {
console.log("Local Tiles Ajax Call", err);
});
}
componentDidMount() {
this.loadData();
}
render() {
return (
<>
<Tile title="1" />
{this.state.tileData.map((item, index) => (
<p key={index}>Hello!</p>
))}
</>
);
}
}
export default GetTiles;
Please note I know it doesn't make sense why I am doing this, but it is to help me understand and debug the issue/Get something working.
{
"_id": "home",
"titles": [
{
"type": "app",
"title": [
{
"text": "Demo",
"locale": "en-gb"
}
],
"data": {
"app_name": "lorem",
"category": "demo"
}
},
{
"type": "app",
"title": [
{
"text": "Demo 2",
"locale": "en-gb"
}
],
"data": {
"app_name": "ipsum",
"category": "sports"
}
}
]
}
I am wanting to be able to target titles within the JSON to get data from it and print out data for each onto the page.
The Error:
A cross-origin error was thrown. React doesn't have access to the actual error object in development. See *** for more information.
Your initial state tileData is an object. You can't forEach or map over an object but that's what you've asked the code to do. It will try to iterate over that state property on the first render which is probably what that error is.
Change
this.state = { tileData: {} }
to
this.state = { tileData: [] }
and then add a condition to your render to return something else if the array is empty, something like:
render() {
if (!this.state.titleData.length) return <div>No data</div>
return this.state.tileData.map(tile => etc
}
First of all you have to change this.state = {tileData: {}, ...} to this.state = {tileData: [],...}.
Your first lines should look like:
constructor(props) {
super(props);
this.state = { tileData: [], dataLoaded: false };
}
I have this json format when I console.log(notes) :
{
"document_tone": {
"tone_categories": [
{
"tones": [
{
"score": 0.027962,
"tone_id": "anger",
"tone_name": "Colère"
},
{
"score": 0.114214,
"tone_id": "sadness",
"tone_name": "Tristesse"
}
],
"category_id": "emotion_tone",
"category_name": "Ton émotionnel"
},
{
"tones": [
{
"score": 0.028517,
"tone_id": "analytical",
"tone_name": "Analytique"
},
{
"score": 0,
"tone_id": "tentative",
"tone_name": "Hésitant"
}
],
"category_id": "language_tone",
"category_name": "Ton de langage"
},
{
"tones": [
{
"score": 0.289319,
"tone_id": "openness_big5",
"tone_name": "Ouverture"
},
{
"score": 0.410613,
"tone_id": "conscientiousness_big5",
"tone_name": "Tempérament consciencieux"
},
{
"score": 0.956493,
"tone_id": "emotional_range_big5",
"tone_name": "Portée émotionnelle"
}
],
"category_id": "social_tone",
"category_name": "Ton social"
}
]
},
"idMedia": 25840
}
this a picture of the console.log(notes), I don't know why I am getting an empty array besides the expected results
but when I try to map tone_categories I get this error :
TypeError: Cannot read property 'map' of undefined
this is the code I've built so far :
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
constructor(props) {
super(props);
this.state = {
notes: [],
};
}
componentWillMount() {
fetch('http://localhost:3000/api/users/analyzeMP3?access_token=GVsKNHWnGWmSZmYQhUD03FhTJ5v80BjnP1RUklbR3pbwEnIZyaq9LmZaF2moFbI6', {
method: 'post',
headers: new Headers({
'Authorization': 'Bearer',
'Content-Type': 'application/x-www-form-urlencoded'
}),
})
.then(response => response.text())
.then(JSON.parse)
.then(notes => this.setState({ notes }));
}
render() {
const { notes } = this.state;
console.log('notes',notes)
return (
<div className="App">
{notes !== undefined && notes !== "" && notes !== [] ? notes.document_tone.map((tone_categories, idx) => {
{console.log('notes',notes.document_tone[tone_categories].category_name)}
}) : null}
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
Your initial state is notes: [], so the array will by empty during the first render and if you try to access an item from an empty array, you get the error.
A better approach in this case would be to have a loading state and defer the render until you have the data fetched:
class App extends Component {
constructor(props) {
super(props);
this.state = {
notes: [],
loading: true // Set the loading to true initially
};
}
componentDidMount() {
fetch(
"http://localhost:3000/api/users/analyzeMP3?access_token=GVsKNHWnGWmSZmYQhUD03FhTJ5v80BjnP1RUklbR3pbwEnIZyaq9LmZaF2moFbI6",
{
method: "post",
headers: new Headers({
Authorization: "Bearer",
"Content-Type": "application/x-www-form-urlencoded"
})
}
)
.then(response => response.text())
.then(JSON.parse)
.then(notes => this.setState({ notes, loading: false })); // reset the loading when data is ready
}
render() {
const { notes, loading } = this.state;
console.log("notes", notes);
return loading ? (
<p>Loading...</p> // Render the loader if data isn't ready yet
) : (
<div className="App">//...</div>
);
}
}
The problem is with this condition notes !== [] which will always return true. If you need to check if an array is empty you can use array.length === 0. Also use componentDidMount instead of componentWillMount because componentWillMount is deprecated.
You can do something like
return (
<div className="App">
{
notes && notes.length > 0 ?
notes.document_tone.map((tone_categories, idx) => {
return notes.document_tone[tone_categories].category_name;
}) : null
}
</div>
);
That is because initially notes as an empty array & does not have document_tone key. So this line will throw error notes.document_tone.map
Add a condition and check if notes have document_tone.
<div className="App">
{
notes !== undefined && notes !== "" && notes !== [] && notes.document_tone.length >0 ?
notes.document_tone.map((tone_categories, idx) => {
{console.log('notes',notes.document_tone[tone_categories].category_name)}
}) :
null}
When you start your application, then the constructor runs, you set the state with notes=[], a render() occurs and prints it in the console.
Then, after willComponentMount(), notes has a new value and triggers a new render().
I am fetching data from a API,then displaying it to the page. I have achieved that,
Now I want to build a next and previous button to render the next page of information.
One of the data returned is metadata to links that can be attached to the base url. I got the data and updated it in my state as:
articlePages: []
the data is structured as :
"metadata": {
"pagination": {
"next_page": "/api/articles/ios_index?page=2",
"current_page": "/api/articles/ios_index?page=1",
"previous_page": "/api/articles/ios_index?page=0"
}
}
How should I build the functions for previous and next, so that they attach the right string to the base url, then fetch the new data?
Here is the response I receive then I update my state:
Response Format:
"metadata": {
"pagination": {
"next_page": "/api/articles/ios_index?page=2",
"current_page": "/api/articles/ios_index?page=1",
"previous_page": "/api/articles/ios_index?page=0"
}
}
"data" :{
"id": 713,
"url": "https:sample.-sale",
"title": "The World According to Eddie Huang",
"published_at": "2017-08-29T04:00:00.000Z",
"published": true,
"hero": "https://d1qz9pzgo5wm5k./CPG9crJHRqSPKQg9jymd",
"listings": [],
"tag_list": [
"eddie-huang",
"television"
],
"franchise": "The Drop",
"slug": "eddie-huang-interview-sale",
"author": "Lawrence Schlossman",
"content_type": "long",
"position": "feature"
}
Here is a snippet of my code, any help is appreciated :
import React from 'react';
import axios from 'axios';
export default class ArticleApi extends React.Component {
constructor() {
super();
this.state = {
blogs: "",
articlePages: []
}
}
fetchData = () => {
axios.get(`https:sample.sale/api/articles/ios_index`)
.then(res => {
this.setState({
blogs: res.data.data,
blogPages: res.data.metadata
})
})
.catch(error => {
return ('Looks like there was a problem: \n', error);
});
}
componentDidMount() {
this.fetchData()
}
previousPage = () => {
axios.get(`https:sample.sale/api/articles/ios_index${this.state.blogPages.pagination.previous_page}`)
.then(res => {
this.setState({
blogs: res.data.data,
blogPages: res.data.metadata
})
})
.catch(error => {
return (error);
});
}
nextPage = () => {
axios.get(`https:sample.sale/api/articles/ios_index${this.state.blogPages.pagination.next_page}`)
.then(res => {
this.setState({
blogs: res.data.data,
blogPages: res.data.metadata
})
})
.catch(error => {
return (error);
});
}
render() {
let feed = "Loading...";
if (this.state.blogs) {
feed = this.state.blogs.map((ele, idx) => {
return (
<div key={idx} >
<div className="articleContent">
<p><strong>{ele.franchise}</strong></p>
<h1 className="title"> {ele.title}</h1>
</div>
</div>
)
})
}
return (
<div>
<h3 FEED</h3>
{feed}
<button onClick={this.previousPage}>Previous Page</button>
<button onClick={this.nextPage}>Next Page</button>
</div>
)
}
}
At present you are building a strange URL for both the next and previous page functions:
axios.get(`https:sample.sale/api/articles/ios_index${this.state.blogPages.pagination.next_page}`)
// but this.state.blogPages.pagination.next_page is equal to "/api/articles/ios_index?page=2", right?
// So if we replace the variable with its value, your url actually looks something like this:
axios.get('https:sample.sale/api/articles/ios_index/api/articles/ios_index?page=2')
The correct call should look like:
axios.get(`https:sample.sale${this.state.blogPages.pagination.next_page}`)
And similarly for previous page.