I have a JSON request, that returns a JSON objects;
{
"kind": "youtube#searchListResponse",
"etag": "zy8y9DkaOiYwKh0aStoEqOU_knU",
"nextPageToken": "CBQQAA",
"regionCode": "GB",
"pageInfo": {
"totalResults": 40,
"resultsPerPage": 20
},
"items": [
{
"kind": "youtube#searchResult",
"etag": "tvnouv0ap06XQKjt95dVECc_VZ4",
"id": {
"kind": "youtube#video",
"videoId": "Qiyk-s60rgo"
},
"snippet": {
"publishedAt": "2020-04-30T10:00:46Z",
"channelId": "UCa_6KiOjxm6dEC_mMRP5lGA",
"title": "Derby Futsal Club - Goal of the Season 2019/20 | Tom Gascoyne vs Birmingham",
"description": "Derby Futsal Club's Goal of the Season as voted for by the public went to Tom Gascoyne for his goal against Birmingham in the National Futsal Series on 3rd ...",
"thumbnails": {
"default": {
"url": "https://i.ytimg.com/vi/Qiyk-s60rgo/default.jpg",
"width": 120,
"height": 90
},
"medium": {
"url": "https://i.ytimg.com/vi/Qiyk-s60rgo/mqdefault.jpg",
"width": 320,
"height": 180
},
"high": {
"url": "https://i.ytimg.com/vi/Qiyk-s60rgo/hqdefault.jpg",
"width": 480,
"height": 360
}
},
"channelTitle": "Derby Futsal",
"liveBroadcastContent": "none",
"publishTime": "2020-04-30T10:00:46Z"
}
},
I'm reading the JSON like so;
useEffect(() => {
fetch(playertype(typeOfProfile))
.then((response) => response.json())
.then((json) => {
setData(json)
})
.catch((error) => console.error(error))
.finally(() => setLoading(false));
}, []);
return (
<View style={styles.body}>
{isLoading ? <ActivityIndicator/> : (
<FlatList
data={data[0]}
horizontal={true}
keyExtractor={({ id }, index) => id}
renderItem={({ item }) => (
<View style={stylesB.container}>
<Image style={styles.img} source={{ uri: chkValueI(item.items.snippet.medium.url) }} />
</View>
)}
/>
)}
</View>
);
};
I'm reading the data as data[0] so I hit the first object, and then finding the property I want (the image) by using item.items.snippet.medium.url, but this doesn't return anything.
My question is;
Can I specify the object I want to get by using data[0] and then reference a property using item.items.snippet.medium.url?
Can I specify the object I want to get by using data[0] and then
reference a property using item.items.snippet.medium.url?
Flat list requires a data array so you dont need a flatlist to display a single item. You can simply use the renderItem function and pass the first item.
item.items.snippet.medium.url
Here the items is an array so you should use something like below to access the item. Better check the array length before doing this. Or go for a map to map the values.
item.items[0].snippet.medium.url
Hope this helps.
Related
Been trying all morning and for the life of me I can't get individual array data to be displayed from my API. I am trying to display one body of text from an array at a time, and can only get it to output all at once. Had it working when the data was in JSON format but now its in an array I'm struggling to make it work.
My code:
componentDidMount() {
axios
.get(
"API_DATA"
)
.then((res) => {
let data = res.data
this.setState({ data, loading: false });
console.log(data)
});
}
render() {
if (this.state.loading) {
return <Loader />
}
// return table if loading is false
// handling error goes with the same logic
// table will only render if loading is false
else
return (
this.state.data.data).map((item) => (
<>
<p key={item.id}>{item.title}</p>
</>
))
}
}
I previously used added [0] or [1] etc to determine which element I wanted to display and this worked very nicely however if I try this.state.data.data[0]).map((item) => ( It states it is not a function.
Expected output of API:
{
"data": [
{
"id": 9,
"status": "published",
"body": "TEST1",
"availability": "internal",
"title": "Test1",
"posted_by": "Tester"
},
{
"id": 10,
"status": "published",
"body": "TEST",
"availability": "internal",
"title": "TEST2",
"posted_by": "Tester"
},
I am mapping over some data that I am getting from a api however when i try to add the filter function i get 'currencyData.includes is not a function'
I have also tried just hard coding the array but it also still doesnt work?
I have a loading state for when i fetch data from the api which holds code from being run but i have removed it from this example as its not getting data from the api below.
The simplified version is here...
ARRAY
var items = [
{
"id": 1,
"productName": "shoes",
"productIdentifier": "CL001",
"productDescription": "adidas kicks boir",
"productPrice": 2000,
"productStock": 200,
"created_at": "2020-51-28",
"updated_at": null
},
{
"id": 2,
"productName": "burger",
"productIdentifier": "FD001",
"productDescription": "charsiu berger",
"productPrice": 2000,
"productStock": 200,
"created_at": "2020-51-28",
"updated_at": null
}
]
return(
{items.filter(currencyInfo => currencyInfo.includes("FD001")).map((value, index) => {
console.log(value)
return(
<h1 key={index}>{value}</h1>
)
})}
)
currencyInfo is not an array, you can not call includes on it
Here is my suggestion:
return(
{items.filter(currencyInfo => currencyInfo.productIdentifier === "FD001").map((value, index) => {
console.log(value)
return(
<h1 key={index}>{value}</h1>
)
})}
)
More about includes()
The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate. Check this Doc
But in items.filter(currencyInfo => currencyInfo.includes("FD001")), type of currencyInfo isn't array but object.
So you should use currencyInfo.productIdentifier.includes()
I am trying to map through some data and display the values from the objects I am mapping through, but it keeps return "[object Object]", usually I just wrap it in JSON.stringify but that isn't working here, what am I doing wrong? Here's my code:
const ListingItem = (props: any) => {
const MOVIE_POSTER_API_URL = "https://image.tmdb.org/t/p/w92/";
const [openMovieDbData, setOpenMovieDbData] = useState<Array<any>>([]);
const [openMovieDbRatings, setOpenMovieDbRatings] = useState([]);
useEffect((): any => {
axios.get(`http://www.omdbapi.com/?t=${props.movie.title}&y=${props.movie.release_date && props.movie.release_date.substr(0, 4)}&apikey=${process.env.REACT_APP_OPEN_MOVIE_API_KEY}`)
.then(response => {
setOpenMovieDbData(response.data);
setOpenMovieDbRatings(response.data.Ratings);
})
.catch((error) => console.log('Open Movie DB HTTP GET Request Error response:', error))
}, [])
return (
<ListItem key={props.movie.id}>
{props.movie.backdrop_path ?
<ListItemAvatar>
<Avatar src={MOVIE_POSTER_API_URL + props.movie.backdrop_path} />
</ListItemAvatar> :
<ListItemIcon>
<Avatar>
<LocalMoviesIcon />
</Avatar>
</ListItemIcon>
}
<ListItemText
primary={props.movie.title}
secondary={`${props.movie.overview} Released in ${props.movie.release_date ? props.movie.release_date.substr(0, 4) : 'N/A'}
${openMovieDbRatings ? openMovieDbRatings.map((rating: any) => <div>{JSON.stringify(rating.Source)}: {JSON.stringify(rating.Value)}</div>) : 'No Reviews'}
Rated: ${openMovieDbData['Rated'] ? openMovieDbData['Rated'] : 'N/A'}
`
}
/>
</ListItem>
)
}
This is an example of what will get returned, in place of [object Object] should be the object values I am trying to access:
Example of response data:
{
"Title": "Braveheart",
"Year": "1995",
"Rated": "R",
"Released": "24 May 1995",
"Runtime": "178 min",
"Genre": "Biography, Drama, History, War",
"Director": "Mel Gibson",
"Writer": "Randall Wallace",
"Actors": "James Robinson, Sean Lawlor, Sandy Nelson, James Cosmo",
"Plot": "Scottish warrior William Wallace leads his countrymen in a rebellion to free his homeland from the tyranny of King Edward I of England.",
"Language": "English, French, Latin, Scottish Gaelic, Italian",
"Country": "USA",
"Awards": "Won 5 Oscars. Another 28 wins & 33 nominations.",
"Poster": "https://m.media-amazon.com/images/M/MV5BMzkzMmU0YTYtOWM3My00YzBmLWI0YzctOGYyNTkwMWE5MTJkXkEyXkFqcGdeQXVyNzkwMjQ5NzM#._V1_SX300.jpg",
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "8.3/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "78%"
}, {
"Source": "Metacritic",
"Value": "68/100"
}],
"Metascore": "68",
"imdbRating": "8.3",
"imdbVotes": "944,923",
"imdbID": "tt0112573",
"Type": "movie",
"DVD": "N/A",
"BoxOffice": "N/A",
"Production": "Icon Entertainment International, Twentieth Century Fox, Ladd Company, Paramount Pictures, B.H. Finance C.V.",
"Website": "N/A",
"Response": "True"
}
i think the issue is here,
secondary={`${props.movie.overview} Released in ${props.movie.release_date ? props.movie.release_date.substr(0, 4) : 'N/A'}
${openMovieDbRatings ? openMovieDbRatings.map((rating: any) => <div>{JSON.stringify(rating.Source)}: {JSON.stringify(rating.Value)}</div>) : 'No Reviews'}
Rated: ${openMovieDbData['Rated'] ? openMovieDbData['Rated'] : 'N/A'}
`}
#1: (main)
${openMovieDbRatings
? openMovieDbRatings.map((rating: any) =>
<div>{JSON.stringify(rating.Source)}: {JSON.stringify(rating.Value)}</div>
)
: 'No Reviews'}
You are mapping openMovieDbRatings and making em ReactElements (aka Objects) by wrapping those inside divs. But, Then u directly pass them to string. This is causing the [object object] thing
#2:
The Rating Object,
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "8.3/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "78%"
}, {
"Source": "Metacritic",
"Value": "68/100"
}],
Here, The Rating Value & Source are strings. So, it unnecessary to JSON.stringify them,
<div>{JSON.stringify(rating.Source)}: {JSON.stringify(rating.Value)}</div>
My Solution,
<ListItemText
primary={props.movie.title}
secondary={
<>
{props.movie.overview} Released in{' '}
{props.movie.release_date
? props.movie.release_date.substr(0, 4)
: 'N/A'}{' '}
{openMovieDbRatings
? openMovieDbRatings.map((rating: any) => (
<div>
{rating.Source}: {rating.Value}
</div>
))
: 'No Reviews'}
Rated:{' '}
{openMovieDbData['Rated'] ? openMovieDbData['Rated'] : 'N/A'}
</>
}
/>
Simply, use React.Fragments.
I'm trying to make an autocomplete/autosuggest search bar from Material-UI through an API response. Here's the codebase annex by annex.
We are defining our options of the autosuggest search bar from the given coinlist API provided. We are defining our options state as well here.
function MainInput() {
const classes = useStyles();
const [options, setOptions] = useState([]);
useEffect(() => {
axios
.get(`https://min-api.cryptocompare.com/data/all/coinlist`)
.then((res) => {
console.log(res.data.Data);
setOptions(res.data.Data);
})
.catch((err) => {
console.log(err);
});
}, []);
Now in the docs from Material-UI for the <Autocomplete /> component. We are supposed to defined our options within the options prop. Theoretically, everything should be fine right? Well, the react app loads fine at first but when I click the searchbar everything disappears from the screen. Can anyone pitch any ideas?
return (
<div className={classes.root}>
<Autocomplete
id='combo-box-demo'
options={options}
getOptionLabel={(options) => options}
style={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label='Combo box' variant='outlined' />
)}
/>
</div>
);
}
Here is what the raw API response looks like for you guys to have an idea.
"Response": "Success",
"Message": "Coin list succesfully returned!",
"Data": {
"42": {
"Id": "4321",
"Url": "/coins/42/overview",
"ImageUrl": "/media/35650717/42.jpg",
"ContentCreatedOn": 1427211129,
"Name": "42",
"Symbol": "42",
"CoinName": "42 Coin",
"FullName": "42 Coin (42)",
"Algorithm": "Scrypt",
"ProofType": "PoW/PoS",
"FullyPremined": "0",
"TotalCoinSupply": "42",
"BuiltOn": "N/A",
"SmartContractAddress": "N/A",
"DecimalPlaces": 0,
"PreMinedValue": "N/A",
"TotalCoinsFreeFloat": "N/A",
"SortOrder": "34",
"Sponsored": false,
"Taxonomy": {
"Access": "",
"FCA": "",
"FINMA": "",
"Industry": "",
"CollateralizedAsset": "",
"CollateralizedAssetType": "",
"CollateralType": "",
"CollateralInfo": ""
},
"Rating": {
"Weiss": {
"Rating": "",
"TechnologyAdoptionRating": "",
"MarketPerformanceRating": ""
}
},
"IsTrading": true,
"TotalCoinsMined": 41.9999522,
"BlockNumber": 200520,
"NetHashesPerSecond": 0,
"BlockReward": 0,
"BlockTime": 0
},{...}
There is an issue with your Data coming from API RESPONSE.
According to Material-UI, the parameter you pass to options should be in an Array but your one is an Object.
Please convert the Data type to Array instead of Object and it will work!
return (
<div className={classes.root}>
<Autocomplete
id='combo-box-demo'
options={options} // this should be in An Array
getOptionLabel={(option) =>option} //go through one option at a time
style={{ width: 300 }}
renderInput={(params) => (
<TextField {...params} label='Combo box' variant='outlined' />
)}
/>
</div>
);
}
Please check the Official Docs of Material-UI
https://material-ui.com/components/autocomplete/
I'm attempting to incorporate video into a flat feed from GetStreamIO. My current approach is to embed a video element from Expo into the content body of the Activity UI component if the post has a video link. Starting with Youtube links only. I'm running into an issue where I'm not able to select the video url when it's available nested in props.activity.attachments. For some reason I cannot directly access the object in the videos array directly without converting the value to JSON. I referenced this StackOverflow Post for the JSON workaround.
My code to check if attachment has video url and grab it if it does
const LikeActivity = (props) => {
if (props.activity.attachments != undefined) {
console.log(props.activity.attachments)
console.log(fetchFromObject(props.activity.attachments, "og"))
var og = fetchFromObject(props.activity.attachments, "og")
var videos = fetchFromObject(og, "videos")
console.log(og)
// Can get the og object but cannot pull video url from it.
}
return (
<Activity
{...props}
Footer={
<View>
// For Now just putting this here to see the video element render. Need to pass URI from Post to element eventually.
<Video
source={{ uri: 'http://d23dyxeqlo5psv.cloudfront.net/big_buck_bunny.mp4' }}
rate={1.0}
volume={1.0}
isMuted={false}
resizeMode="cover"
shouldPlay
isLooping
style={{ width: 300, height: 300 }}
/>
<LikeButton {...props} />
</View>
}
/>
);
};
My App implementation
<StreamApp
apiKey="XXXX"
appId="XXXX"
token="XXXXXX"
>
<FlatFeed
feedGroup="timeline"
userId="user-one"
Activity={LikeActivity}
/>
</StreamApp>
Fetch From Object method
function fetchFromObject(obj, prop) {
if(typeof obj === 'undefined') {
return false;
}
var _index = prop.indexOf('.')
if(_index > -1) {
return fetchFromObject(obj[prop.substring(0, _index)], prop.substr(_index + 1));
}
return obj[prop];
}
The feed consists of a number of posts and the props.activity.attachments has the following values at runtime. Each post with a link currently has a rich snippet. The attachments value also recognizes videos vs images. I've also included an image of the feed here as a reference.
Object {
"og": Object {
"description": "Why choose one when you can wear both? These energizing pairings stand out from the crowd",
"images": Array [
Object {
"image": "https://www.rollingstone.com/wp-content/uploads/2018/08/GettyImages-1020376858.jpg",
},
],
"title": "'Queen' rapper rescheduling dates to 2019 after deciding to “reevaluate elements of production on the 'NickiHndrxx Tour'",
"url": "https://www.rollingstone.com/music/music-news/nicki-minaj-cancels-north-american-tour-with-future-714315/",
},
}
undefined
Object {
"og": Object {
"description": "Why choose one when you can wear both? These energizing pairings stand out from the crowd",
"images": Array [
Object {
"image": "https://images.wsj.net/im-21927/TOP",
},
],
"title": "How to Pair Neutrals and Bright Colors",
"url": "https://graphics.wsj.com/glider/marketreport-4a039902-7e0d-4631-ab83-6cc1931c1bc6",
},
}
undefined
Object {
"og": Object {
"description": "Serial entrepreneur Elon Musk wants to fundamentally change the way we live. But his path to success has been characterized by both great accomplishments and flirtations with failure.",
"images": Array [
Object {
"image": "https://static01.nyt.com/images/2018/08/22/us/19xp-musk-vid-2/19xp-musk-vid-2-videoSixteenByNine1050.jpg",
},
],
"title": "Elon Musk’s Highs and Lows: PayPal, SpaceX, Tesla",
"url": "https://www.nytimes.com/video/business/100000006060092/elon-musk-tesla-spacex.html",
},
}
undefined
Object {
"og": Object {
"description": "We are in a Simulation - Elon Musk",
"images": Array [],
"site_name": "YouTube",
"title": "We are in a Simulation - Elon Musk",
"type": "video.other",
"url": "https://www.youtube.com/watch?v=xBKRuI2zHp0",
"videos": Array [
Object {
"height": "360",
"secure_url": "https://www.youtube.com/embed/xBKRuI2zHp0",
"type": "text/html",
"width": "640",
},
],
},
}
Array [
Object {
"height": "360",
"secure_url": "https://www.youtube.com/embed/xBKRuI2zHp0",
"type": "text/html",
"width": "640",
},
]
Object {
"images": Array [
"https://cdn.vox-cdn.com/thumbor/OBDFDT9j-nHEpGLckE4u5ibX2qU=/1400x1400/filters:format(png)/cdn.vox-cdn.com/uploads/chorus_asset/file/13589869/edu_distance_to_the_moon.png",
"https://www.jpl.nasa.gov/images/mars/20170622/PIA01466-16.jpg",
"http://cdn.sci-news.com/images/enlarge4/image_5608_2e-Jupiter.jpg",
"https://d2r55xnwy6nx47.cloudfront.net/uploads/2018/07/SolarFull_SeanDoran_2880FullwidthLede-2880x1620.jpg",
],
}