How can I get all results in ReactiveList - javascript

I've tried to use on all data but it doesn't work since I can get only the number of results as stated in the 'size' parameter. Here part of my code.
<ReactiveList
componentId="results"
dataField="original_title"
size={1}
showResultStats={true}
pagination={true}
react={{
and: "searchbox"
}}
onAllData={this.onAllData}
/>
onAllData(shops) {
let result = null;
if (shops !== null) {
console.log(shops.length);
result = shops.map((marker) => (
<ListItem>
<Thumbnail square size={80} source={{ uri: 'https://dummyimage.com/80x80/000/fff' }} />
<Body>
<Text>{marker.name}</Text>
<Text note>{marker.dis}</Text>
</Body>
</ListItem>
))
return result;
}
}

There are a couple of ways you can go about this problem:
Rendering all results with infinite loading
onAllData will give the number of results specified in the size prop. Usually, its not a good idea to set a very high size since it will take more time fetching and rendering the results. A good alternative for this is to use infinite scrolling by setting the pagination prop to false and setting a value in size prop which tells the component how many results to fetch when you reach the end of the list.
Fetching all results using scroll API
tl;dr Demo
Note
This answer uses reactivesearch for web (for demonstration) but you can use the same props in reactivesearch-native since the API is same.
The above approach works fine if you're only interested in rendering the results. But if you wish to fetch all the results for the current query, you can use the scroll API from Elasticsearch. You can use ReactiveList to get the current query and then use it together with the scroll API.
For this purpose, you can make use of the onQueryChange prop on ReactiveList:
First specify an onQueryChange prop on the ReactiveList which receives the previous and current query as parameters:
onQueryChange={(prev, next) => ...}
This function will be invoked each time the query is changed so you can write a logic to fetch the hits for the current query (received in the next parameter) whenever required.
A scroll API call returns the results in the following format:
{
"_scroll_id": "DnF1ZXJ5VGhlbkZldGNoAgAAAAClGlY4FlotbmJJZXA0U09lMlZFMUNyQ3M2M0EAAAAApRpWORZaLW5iSWVwNFNPZTJWRTFDckNzNjNB",
"took": 0,
"timed_out": false,
"_shards": {
"total": 2,
"successful": 2,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 9407,
"max_score": 1,
"hits": [
{
"_index": "good-books-ds",
"_type": "good-books-ds",
"_id": "5676",
"_score": 1,
"_source": {
"authors": "Arthur C. Clarke, Gentry Lee",
"average_rating": 3.76,
"average_rating_rounded": 4,
"books_count": 48,
"id": 5676,
"image": "https://images.gr-assets.com/books/1375814957l/112518.jpg",
"image_medium": "https://images.gr-assets.com/books/1375814957m/112518.jpg",
"isbn": "1857230213",
"language_code": "eng",
"original_publication_year": 1991,
"original_series": "Rama",
"original_title": "The Garden of Rama (Rama, #3)",
"ratings_count": 16389,
"title": "The Garden of Rama (Rama, #3)"
}
},
{
"_index": "good-books-ds",
"_type": "good-books-ds",
"_id": "5681",
"_score": 1,
"_source": {
"authors": "Darren Shan",
"average_rating": 4.22,
"average_rating_rounded": 4,
"books_count": 52,
"id": 5681,
"image": "https://s.gr-assets.com/assets/nophoto/book/111x148-bcc042a9c91a29c1d680899eff700a03.png",
"image_medium": "https://s.gr-assets.com/assets/nophoto/book/111x148-bcc042a9c91a29c1d680899eff700a03.png",
"isbn": "",
"language_code": "",
"original_publication_year": 2003,
"original_series": "Cirque Du Freak",
"original_title": "Killers of the Dawn (Cirque Du Freak, #9)",
"ratings_count": 18194,
"title": "Killers of the Dawn (Cirque Du Freak, #9)"
}
},
{
"_index": "good-books-ds",
"_type": "good-books-ds",
"_id": "5683",
"_score": 1,
"_source": {
"authors": "Laura Joffe Numeroff, Felicia Bond",
"average_rating": 4.16,
"average_rating_rounded": 4,
"books_count": 13,
"id": 5683,
"image": "https://s.gr-assets.com/assets/nophoto/book/111x148-bcc042a9c91a29c1d680899eff700a03.png",
"image_medium": "https://s.gr-assets.com/assets/nophoto/book/111x148-bcc042a9c91a29c1d680899eff700a03.png",
"isbn": "60278684",
"language_code": "",
"original_publication_year": 2000,
"original_series": "",
"original_title": "If You Take a Mouse to the Movies",
"ratings_count": 17938,
"title": "If You Take a Mouse to the Movies"
}
},
{
"_index": "good-books-ds",
"_type": "good-books-ds",
"_id": "5685",
"_score": 1,
"_source": {
"authors": "Orson Scott Card, James Cameron",
"average_rating": 4.06,
"average_rating_rounded": 4,
"books_count": 15,
"id": 5685,
"image": "https://images.gr-assets.com/books/1225165505l/40289.jpg",
"image_medium": "https://images.gr-assets.com/books/1225165505m/40289.jpg",
"isbn": "99690608",
"language_code": "eng",
"original_publication_year": 1989,
"original_series": "",
"original_title": "The Abyss",
"ratings_count": 16318,
"title": "The Abyss"
}
},
{
"_index": "good-books-ds",
"_type": "good-books-ds",
"_id": "5687",
"_score": 1,
"_source": {
"authors": "Katarina Bivald, Alice Menzies",
"average_rating": 3.56,
"average_rating_rounded": 4,
"books_count": 63,
"id": 5687,
"image": "https://images.gr-assets.com/books/1452107441l/25573977.jpg",
"image_medium": "https://images.gr-assets.com/books/1452107441m/25573977.jpg",
"isbn": "149262344X",
"language_code": "eng",
"original_publication_year": 2013,
"original_series": "",
"original_title": "Läsarna i Broken Wheel rekommenderar",
"ratings_count": 14571,
"title": "The Readers of Broken Wheel Recommend"
}
}
]
}
}
The value received as _scroll_id can be passed to the scroll API to fetch the next set of results and so on till the number of hits is zero.
Note
If your cluster has a lot of data, its not a good idea to run this logic to fetch all the results every time the query changes. You can add a condition to limit the number of results fetched or store the current query in state and only fetch all the results when required.
Here's an example on how you can implement this with ReactiveList. In the example I'm fetching the results each time the query changes but you can modify it to fetch results conditionally instead:
In your render function:
<ReactiveList
...
size={10}
onQueryChange={this.handleQueryChange}
/>
Here's how the handleQueryChange function can look like. This will give you all the results for the current query:
handleQueryChange = async (prev, next) => {
// avoid fetching the results for match_all query since dataset is large
if (next && !next.query.match_all) {
console.log('Fetching all results for query:', next);
// modify the query size here if needed (currently it is 10)
// initial url to obtain scroll id is different
const initialResults = await this.fetchResults(next, url);
// keep scrolling till hits are present
// NOTE: careful if you've a lot of results,
// in that case you might want to add a condition to limit calls to scroll API
const scrollResults = await this.fetchScrollResults({
scroll: "1m",
scroll_id: initialResults._scroll_id
});
// combine the two to get all results
// concat hits from initialResults with hits from scrollResults
const allResults = initialResults.hits.hits.concat(scrollResults);
console.log(`${allResults.length} results found:`, allResults);
}
};
Its using two functions for fetching the results initially and later with the scroll_id. The endpoints for both are different, which you can find in the demo. Here's how the first fetchResults looks like:
fetchResults = (query, api) => {
return fetch(api, {
method: "POST",
headers: {
"content-type": "application/json",
Authorization: `Basic ${btoa(credentials)}`
},
body: JSON.stringify(query)
})
.then(res => res.json())
.catch(err => console.error(err));
};
The fetchScrollResults will use the scroll API to fetch results till the hits obtained are 0.
fetchScrollResults = async query => {
const res = await this.fetchResults(query, scrollUrl);
const { hits } = res.hits;
if (hits.length) {
return [
...hits,
...(await this.fetchScrollResults({
scroll: "1m",
scroll_id: res._scroll_id
}))
];
}
return [];
};
Check the demo, results will appear in the console.

You are missing a key that identify unique components and you also need to wrap element inside function. If function is called properly and your array have elements this should work.
onAllData(shops) {
let result = null;
if (shops !== null) {
console.log(shops.length);
result = shops.map((marker,index) => { return (
<ListItem key={index}>
<Thumbnail square size={80} source={{ uri: 'https://dummyimage.com/80x80/000/fff' }} />
<Body>
<Text>{marker.name}</Text>
<Text note>{marker.dis}</Text>
</Body>
</ListItem>
)})
return result;
}

Related

Changing date value in object in Node

For example i have a get request which takes some data from mongo db:
const getAllContracts = async (req, res) => {
const contracts = await Contract.find({});
res.status(StatusCodes.OK).json({ contracts, count: contracts.length });
};
As response it sends:
{
"contracts": [
{
"_id": "637cbd3279de1dd12dd7d2f9",
"tenant": "Nazar",
"manager": "Misha",
"object": "Автовокзал",
"price": 99,
"area": 335,
"status": "Активний",
"activeFrom": "2022-11-16T00:00:00.000Z",
"activeUntil": "2022-11-18T00:00:00.000Z",
"createdBy": "6372c4bc0c02f9ccf3363fe0",
"contractManualId": "321a",
"contractReason": "IDK",
"contractComment": "Vasya",
"createdAt": "2022-11-22T12:14:42.248Z",
"updatedAt": "2022-11-22T12:14:42.248Z",
"__v": 0
},
{
"_id": "637cbd4d79de1dd12dd7d2fc",
"tenant": "Nazar1111",
"manager": "Misha",
"object": "Автовокзал",
"price": 99,
"area": 335,
"status": "Активний",
"activeFrom": "2022-11-16T00:00:00.000Z",
"activeUntil": "2022-11-18T00:00:00.000Z",
"createdBy": "6372c4bc0c02f9ccf3363fe0",
"contractManualId": "321a",
"contractReason": "IDK",
"contractComment": "Vasya",
"createdAt": "2022-11-22T12:15:09.755Z",
"updatedAt": "2022-11-22T12:15:09.755Z",
"__v": 0
}
],
"count": 2
}
I would like to change response date formats in activeFrom and activeUntil to dd-mm-yyyy but idk how to do that. For example 2022-11-16T00:00:00.000Z i want to change to 16.11.2022
Simple answer:
Loop over contracts and modify the properties
contracts.map((contract) => {
const activeFromDate = new Date(contract.activeFrom);
contract.activeFrom = formatDate(activeFromDate);
const activeUntilDate = new Date(contract.activeUntil);
contract.activeUntil = formatDate(activeUntilDate);
return contract;
});
function formatDate(date) {
// the +1 is because getMonth is zero-based.
return `${date.getDate()}.${date.getMonth() + 1}.${date.getFullYear()}`
}
But couple of thoughts:
1.) If you're passing this to UI code it would be "cleaner" for the UI to do this formatting.
2.) IF you have to do this on the backend return both the formatted and raw data rather than the inplace update like above.
So same structure but instead of assigning to contract.activeFrom you should assign the resultant to contract.formattedActiveFrom and return both properties to the UI. That way if they need to do any additional tinkering with the date they have it available in a format that's easy to use.

Looping through array, fetching tweets and returning new reversed array javascript react

UPDATE: I have deployed the site for more context you can view it here https://conundrum-quest-rw-rebuild-web.onrender.com/
the public repo is here
https://github.com/wispyco/conundrum-quest-rw-rebuild
Note: the data on the live site is different but the initial load is loading the hero's on the wrong cards, you can compare the quest with subsequent heros on the home page and the returned data from my function below, you can scroll down to see the rendered cards.
You can see that if you click on a card it shows the correct heros on the single page.
I have the following quests data structure that I am looping through in a separate function and running a fetch to request some profile images from twitter.
[
{
"__typename": "Quest",
"id": 5,
"name": "How do we solve mental health related issues?",
"userId": 17,
"heros": [
{
"__typename": "Hero",
"name": "Anders Kitson",
"twitter": "anderskitson"
},
{
"__typename": "Hero",
"name": "ders",
"twitter": "derz_O"
}
]
},
{
"__typename": "Quest",
"id": 6,
"name": "How do we create a world where North Korea participates and collaborates with the rest of the World?",
"userId": 17,
"heros": [
{
"__typename": "Hero",
"name": "Crypto Dude",
"twitter": "phunk2243"
}
]
}
]
Here is my custom hook
const twitter = useFetchTwitterMultipleQuests(quests)
export const useFetchTwitterMultipleQuests = (twitterProfileManyQuests) => {
const [twitter, setTwitter] = useState([])
useEffect(() => {
twitterProfileManyQuests.forEach(async (twitterProfileMany, i) => {
const woop = twitterProfileMany.heros.map(async (twitterProfile) => {
const test = fetch(
`${window.location.origin}/.redwood/functions/twitter`,
{
method: 'POST',
body: JSON.stringify({ twitter: twitterProfile.twitter }),
}
)
.then(function (response) {
// The response is a Response instance.
// You parse the data into a useable format using `.json()`
console.log('test')
return response.json()
})
.then(function (data) {
return data.data.resultAwaited.data
})
const go = await test
return go
})
const june = await Promise.all(woop)
setTwitter((prevState) => {
return [...prevState, june]
})
})
}, [twitterProfileManyQuests])
const reversedTwitter = twitter.reverse()
return reversedTwitter
}
The problem is the reversedTwitter or twitter variable in the end sometimes is in the correct reversed order and sometimes not reversed, and I can't figure out why.
This is the correct order result
[
[
{
"username": "anderskitson",
"profile_image_url": "https://pbs.twimg.com/profile_images/1428160652237889539/I7ZiM_g8_normal.jpg",
"name": "▲nders on a quest 🜸 to see myself 🪞",
"id": "4633808432"
},
{
"profile_image_url": "https://pbs.twimg.com/profile_images/1496985668043436033/NoyLrUys_normal.jpg",
"name": "ders.eth",
"id": "1389695824934834181",
"username": "derz_O"
}
],
[
{
"username": "phunk2243",
"profile_image_url": "https://pbs.twimg.com/profile_images/1536485988767350784/cfP_sPSC_normal.jpg",
"name": "9999999333 (🅱️uilding 35 Phunks) 🔜",
"id": "1355005208259133442"
}
]
]
This is the incorrect order result
[
[
{
"name": "9999999333 (🅱️uilding 35 Phunks) 🔜",
"profile_image_url": "https://pbs.twimg.com/profile_images/1536485988767350784/cfP_sPSC_normal.jpg",
"username": "phunk2243",
"id": "1355005208259133442"
}
],
[
{
"username": "anderskitson",
"profile_image_url": "https://pbs.twimg.com/profile_images/1428160652237889539/I7ZiM_g8_normal.jpg",
"name": "▲nders on a quest 🜸 to see myself 🪞",
"id": "4633808432"
},
{
"username": "derz_O",
"profile_image_url": "https://pbs.twimg.com/profile_images/1496985668043436033/NoyLrUys_normal.jpg",
"name": "ders.eth",
"id": "1389695824934834181"
}
]
]
The reason this matters is how I am rendering the data. I am rendering a Quest from the quests data, then mapping over the heros in a quest which correspond to the twitter profiles.
See Here
{quests.map((quest, i) => (
<QuestCard key={quest.id}>
<Link to={routes.quest({ id: quest.id })} key={quest.id}>
<div>
<h3>{truncate(quest.name)}</h3>
{quest.heros.map((hero, index) => (
<React.Fragment key={hero.id}>
{twitter.length > 0 && twitter[i] && (
<span>
{hero.name}
<p>{twitter[i][index]?.name}</p>
<img
key={i}
src={twitter[i][index]?.profile_image_url}
alt={twitter[i][index]?.name}
/>
</span>
)}
</React.Fragment>
))}
</div>
</Link>
<div className="clear" />
</QuestCard>
))}
Any help would be greatly appreciated, most of what I have done works, but after about three refreshes the ordering breaks. Thanks
Fixed by using a custom service and a custom sdl in redwood instead of using a function and having to create a custom hook for rendering. This was recommended by the RW team from this article
https://redwoodjs.com/docs/how-to/using-a-third-party-api
And you can see my changes here
https://github.com/wispyco/conundrum-quest-rw-rebuild/pull/8/commits/41637813dd50be70e2e89372606c08e39618fa07

Can't access the data of Facebook Graph Api response - reactJs

I tried all the day to find a solution on how I can access Facebook nested response.
I use FB.api with a nested request and I got the response and it is ok.
Here a sample of the Response I got from Facebook Graph Api
{
"insights": {
"data": [
{
"name": "page_fan_adds_unique",
"period": "month",
"values": [
{
"value": 272,
"end_time": "2019-10-08T07:00:00+0000"
},
{
"value": 270,
"end_time": "2019-10-09T07:00:00+0000"
}
],
"title": null,
"description": "The number of new people who have liked your Page.",
"id": "1021596371302281/insights/page_fan_adds_unique/month"
},
{
"name": "page_fan_removes_unique",
"period": "month",
"values": [
{
"value": 450,
"end_time": "2019-10-08T07:00:00+0000"
},
{
"value": 453,
"end_time": "2019-10-09T07:00:00+0000"
}
],
"title": null,
"description": "Unlikes of your Page.",
"id": "1021596371302281/insights/page_fan_removes_unique/month"
},
{
"name": "page_views_total",
"period": "month",
"values": [
{
"value": 6430,
"end_time": "2019-10-08T07:00:00+0000"
},
{
"value": 6339,
"end_time": "2019-10-09T07:00:00+0000"
}
],
"title": null,
"description": "The number of times a Page's profile has been viewed by logged in and logged out people.",
"id": "1021596371302281/insights/page_views_total/month"
}
],
i'm using react. I made the APi call in the parent component like so :
async componentDidMount() {
const resI = await axios.get(
'https://graph.facebook.com/MyID/',
{
params: {
access_token: process.env.REACT_APP_FACEBOOK_ACCESS_TOKEN,
fields:
'insights.metric(page_fans, post_engaged_users, post_impressions_unique, page_fan_adds_unique, page_fan_removes_unique, page_views_total, page_fans_gender_age, page_fans_country, page_fans_city, page_fans_locale).period(month)'
}
}
);
this.setState({insights: resI.data});
console.log(this.state.insights.insights.data[0].values[1].value); //I Get 270. It working in the parent component
}
I past the data I got from the API as a props to my other components
....
<div>
<GlobalPerf insights={this.state.insights} />
</div>
......
Here is where the problem start. I can't access value in the values array within my child that components
class GlobalPerf extends Component {
render() {
const ins = this.props.insights; // I can't go deeper than that.
console.log(ins.insights);
I can't access the value in the object. I can't go deeper than this.props.insights
When I try this.props.insights.data it not working. Can someone help me figuring out ? Thx
this.setState({insights: resI.data});
console.log(this.state.insights.insights.data[0].values[1].value); //I Get 270. It working in the parent component
The above statements should not work, since the setState is asynchronous and does not update the value synchronously. Probably showing the old state value?
setState() does not immediately mutate this.state but creates a pending state transition. Accessing this.state after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to setState and calls may be batched for performance gains.
You may be trying to access the props.insights before axios completes
const ins = this.props.insights; // probably wait for the axios to complete the fetch before trying to access the value! write it as
console.log(ins && ins.insights); //will give insights once the component rerenders after the props change due to the state being updated in the parent after axios returns!

How to read object URI (JSON file) from JSON file

I am able to read this JSON file but I am not able to read object URI JSON file. How can I use Object URI JSON File?
And this is the way I tried to read Uri JSON object
componentDidMount(){
const { match: { params } } = this.props;
axios.get(params.uri).then((res)=>{
const question = res.data[0]['uri'];
console.log(question);
this.setState({ question });
})
}
This is JSON file where Object URI contains a JSON file so how to read
[
{
"id": 59413,
"thumbnail": {
"id": "60255",
"title": "dornoch-castle-whisky-bar",
"alt": "dornoch-castle-whisky-bar",
"url": "https://media-magazine.trivago.com/wp-content/uploads/2019/01/23144800/dornoch-castle-whisky-bar.jpg",
"courtesy": "",
"position": "center"
},
"thumbnail_url": "https://media-magazine.trivago.com/wp-content/uploads/2019/01/23144800/dornoch-castle-whisky-bar.jpg",
"slug": "dornoch-castle-scotland-whisky",
"uri": "http://trivago-magazine-work-sample-server.s3-website.eu-central-1.amazonaws.com/dornoch-castle-scotland-whisky.json",
"title": "Dornoch Castle: A Whisky Tasting at One of the World's Most Popular Hotel Bars",
"card_title": "Whisky Tasting at Dornoch Castle in the Scottish Highlands",
"show_publish_date": false,
"date": "January 29th, 2019",
"newsletter_popup": false,
"newsletter_popup_header_image": false,
"taxonomies": {
"destinations": [
{
"name": "Europe",
"uri": "/destination/international/europe",
"slug": "europe",
"term_id": 1384
}
],
"themes": [],
"types": [
{
"name": "Nature",
"uri": "/type/nature",
"slug": "nature",
"term_id": 1380
}
]
},
"excerpt": "Dornoch Castle has amassed a whisky collection unlike most any other in the world. trivago Magazine Editor, Joe Baur, signs up for their whisky tasting. Video below."
},
Using the same way you extracted the first uri json data, fire another request to get the data from the second uri = res.data[0]['uri']
componentDidMount(){
const { match: { params } } = this.props;
axios.get(params.uri).then((res)=>{
const question = res.data[0]['uri'];
axios.get(question).then((qRes) => {
console.log(qRes); //will return the data from the second uri
})
console.log(question);
this.setState({ question });
})
}
I think this is just a normal JSON. You can get the file by reading direct to field url and thumnail_url
"url": "https://media-magazine.trivago.com/wp-content/uploads/2019/01/23144800/dornoch-castle-whisky-bar.jpg",
You can show this file by
<img src="https://media-magazine.trivago.com/wp-content/uploads/2019/01/23144800/dornoch-castle-whisky-bar.jpg" />

Fetch specific data from API ReactJS

I'm trying to fetch specific data from a API, something like that:
I have that JSON after response:
{
"id": 5,
"url": "http://127.0.0.1:8000/api/article/5/",
"title": "Obama Offers Hopeful Vision While Nothing Nation's Fears",
"description": "Obama Offers Hopeful Vision While Nothing Nation's Fears",
"category": [
"http://127.0.0.1:8000/api/category/1/"
],
"image": "http://127.0.0.1:8000/media/article_image/news_01_3MT46Rk.jpg"
},
{
"id": 6,
"url": "http://127.0.0.1:8000/api/article/6/",
"title": "NASA Formalizes Efforts To Protect Earth From Asteroids",
"description": "Last week, NASA annouced a new program called the Planetary Defense Coordination Office (PDCO) which will coordinate NASA's efforts for detecting and tracking near-Earth objects (NEOs), If a large object comes hurting toward our planet...",
"category": [
"http://127.0.0.1:8000/api/category/4/"
],
"image": "http://127.0.0.1:8000/media/article_image/news_03_EOUms51.jpg"
},
{
"id": 7,
"url": "http://127.0.0.1:8000/api/article/7/",
"title": "Didi Kuaidi, The Company Beating Uber In China, Opens Its API To Third Party Apps",
"description": "One day after Uber updated its API to add 'content experiences' for passengers, the U.S company's biggest rival - Didi Kuadii in China - has opened its own platform up by releasing an SDK for developoers and third-parties",
"category": [
"http://127.0.0.1:8000/api/category/3/"
],
"image": "http://127.0.0.1:8000/media/article_image/news_02_l5zY4HJ.jpg"
}
And in that API, i have a child called by Category:
{
"id": 1,
"url": "http://127.0.0.1:8000/api/category/1/",
"name": "POLITICS"
},
{
"id": 2,
"url": "http://127.0.0.1:8000/api/category/2/",
"name": "BUSINESS"
},
{
"id": 3,
"url": "http://127.0.0.1:8000/api/category/3/",
"name": "TECH"
},
{
"id": 4,
"url": "http://127.0.0.1:8000/api/category/4/",
"name": "SCIENCE"
},
{
"id": 5,
"url": "http://127.0.0.1:8000/api/category/5/",
"name": "SPORTS"
}
What i want to do is to render my articles with the POLITICS category, but I'dont know how to do that, Here is what I've done so far.
Method to fetch json:
getItems() {
this.setState({ 'isLoading': true });
fetch('http://127.0.0.1:8000/api/article/')
.then(results => {
if (results.ok) {
return results.json();
} else {
throw new Error('Something went wrong ...');
}
})
.then(results => this.setState({ 'items': results, 'isLoading': false }))
.catch(error => this.setState({ error, isLoading: false }));
}
My render method:
render() {
const { isLoading, error } = this.state;
if (error) {
return <p>{error.message}</p>;
}
if (isLoading) {
return <p>Loading ...</p>;
}
return (
<ul>
{this.state.items.map(function (item, index) {
console.log(item.category.indexOf("1") != 01)
if (item.category === 1){
return <ContentItem item={item} key={index} />
}
})}
</ul>
);
}
EDIT: Output from console.log(item) in render:
{id: 5, title: "Obama Offers Hopeful Vision While Nothing Nation's Fears", description: "Obama Offers Hopeful Vision While Nothing Nation's Fears", category: Array(1), image: "http://127.0.0.1:8000/media/article_image/news_01_3MT46Rk.jpg"}
category: Array(1)
0: 1
length: 1
__proto__: Array(0)
description: "Obama Offers Hopeful Vision While Nothing Nation's Fears"
id: 5
image: "http://127.0.0.1:8000/media/article_image/news_01_3MT46Rk.jpg"
title: "Obama Offers Hopeful Vision While Nothing Nation's Fears"
__proto__: Object
What you are NOT doing, is filtering by id,
if (item.category === 1){ //You need to add .id here
return <ContentItem item={item} key={index} />
}
like so:
if (item.category.id === 1){ //.id
return <ContentItem item={item} key={index} />
}
What you are doing wrong is that you are checking the whole object against the === 1 condition instead of just the property id of the object.

Categories