React.map defined but says undefined - javascript

UPDATE:
by the way I'm already defined the data with the response in
setState({ fetchedData: responseJSON.data })
I’m just getting the response data in setState called fetchedData: [] I’m wondering why I’m getting an error while I’m fetching movies from this.state.fetchedData even though if I did console log for this.state.fetchedData I’m getting this data
{
"data":{
"title": "The Basics - Networking",
"description": "Your app fetched this from a remote endpoint!",
"movies": [
{ "id": "1", "movieTitle": "Star Wars", …},
{ "id": "2", "movieTitle": "Back to the Future", …}
{ "id": "3", "movieTitle": "The Matrix", …}
{ "id": "4", "movieTitle": "Inception", …},
{ "id": "5", "movieTitle": "Interstellar", …}
]
}
}
Also if I did console log for this.state.fetchedData.movies I’m getting response
[
{ "id": "1", "movieTitle": "Star Wars", …},
{ "id": "2", "movieTitle": "Back to the Future", …}
{ "id": "3", "movieTitle": "The Matrix", …}
{ "id": "4", "movieTitle": "Inception", …},
{ "id": "5", "movieTitle": "Interstellar", …}
]
I have tried to use map it doesn’t work here’s my code
const allNews = this.state.fetchedData.movies.map((data) =>
<ul>
<li key={data.id}>{data.total}</li>
</ul>
);
I’m getting error says Cannot read property 'map' of undefined
Then I did a big research I got I should use object.key here’s my code:
const getData = this.state.fetchedData.map((items, index) => {
return (
<ul key={index}>
{Object.keys(items.movies).map((movie) => {
return (
<li key={movie.id}>{key.movieTitle}</li>
)
})}
</ul>
)
});
I’m getting error says
this.state.fetchedData.map is not a function
I really don’t know where’s my problem even though if I console log the Data I’m getting correct response
Thank you guys for helping me

You are not traversing through your state correctly, this will solve your problem.
const allNews = this.state.fetchedData.data.movies.map((data) =>
<ul>
<li key={data.id}>{data.total}</li>
</ul>
);

How is it that when printing this.state.fetchedData.movies you get { movies: [ ... ] }? Going by the shape of this.state.fetchedData you should only get the array in movies, but are getting an object that has a movies key inside.
Have you tried this.state.fetchedData.movies.movies.map?
How is it that this.state.fetchedData.movies isn't only the movies array? If it's an object no surprise you can't call map on it.
When are you calling setState({ fetchedData: responseJSON.data })? When is this.state.fetchedData.movies.map called? How can you be sure the state is set with fetchedData in the initial render?

Related

How to map through nested objects of Laravel collection in React JS

In my front-end I am trying to map through nested objects which is coming from back-end Laravel collection:
[
{
"id": 1,
"name": "Chips",
"product_categories_id": 1,
"category": {
"id": 1,
"category": "Chips",
"brand": "Bombay Sweets"
}
},
{
"id": 2,
"name": "Book",
"product_categories_id": 2,
"category": {
"id": 2,
"category": "Shoe",
"brand": "Nike",
}
}]
I want to display the product name and related category name from nested object. My approach is:
products.map((product)=>{
console.log(product.name)
product.category.map((category)=>(
console.log(category.category)
))
})
which is not working at all. I spent huge amount of time to solve yet no luck.
the error it shows:
ProductListContainer.js:58 Uncaught TypeError: item.category.map is not a function
map method works only with Array. You can use product.category.category to access the value.
Finally solved by this:
products.map((product) => {
console.log(product.name)
Object.entries(product.category).map(() => (
console.log(product.category.category, product.category.brand)
))
})

How to reach multiple elements in an array without using axios

Yesterday i saw a React project on youtube and i wanted to test it myself.
This function connects to the link and returns me the questions of the category and difficulty I selected with my buttons . code works fine ,but i don't want to do that step with axios and any API related stuff.
const fetchQuestions = async (category = "", difficulty = "") => {
const { data } = await axios.get(
`https://opentdb.com/api.php?amount=10${
category && `&category=${category}`
}${difficulty && `&difficulty=${difficulty}`}&type=multiple`
);
console.log(category);
console.log(difficulty);
setQuestions(data.results);};
I only want to see the questions in the difficulty and category I chose .
So i created a json file and tried to get those questions&answers etc. with that but it didn't work . I tried to map things inside and log category and difficulty but i can't even reach those . I know that i need some conditions etc. but i can't create the logic .
const fetchQuestions =(category="",difficulty="")=>{const {data}=QuestionList.results.map((q)=> (console.log(category),console.log(q[category]),console.log(data),console.log(q[difficulty]))); setQuestions(data.results);}
this is json file : questions.json -> i imported as QuestionList
{
"response_code": 0,
"results": [
{
"category": "Books",
"type": "multiple",
"difficulty": "medium",
"question": "some question?",
"correct_answer": "blabla",
"incorrect_answers": ["Transformers", "Care Bears", "Rubik’s Cube"]
},
{
"category": "Books",
"type": "multiple",
"difficulty": "easy",
"question": "sdklgksdflgjsdf",
"correct_answer": "Badminton",
"incorrect_answers": ["Table Tennis", "Rugby", "Cricket"]
},
{
"category": "Books",
"type": "multiple",
"difficulty": "medium",
"question": "fgdfgdfgdfgdfgg?",
"correct_answer": "9",
"incorrect_answers": ["6", "10", "3"]
},
{
"category": "Films",
"type": "multiple",
"difficulty": "medium",
"question": "asdasdasdasd",
"correct_answer": "Parlor",
"incorrect_answers": ["Open Room", "Sitting Room", "Loft"]
},
{
"category": "Films",
"type": "multiple",
"difficulty": "medium",
"question": "asdasdasddddd",
"correct_answer": "Link",
"incorrect_answers": ["Wario", "Q*bert", "Solid Snake"]
}
]}
I've been stuck on this for 9 hours but i still have no solution :)
Issue
const fetchQuestions = (category = "", difficulty = "") => {
const { data } = QuestionList.results.map(
(q) => (
console.log(category),
console.log(q[category]),
console.log(data),
console.log(q[difficulty])
)
);
setQuestions(data.results);
};
The code above is calling the Array.prototype.map function but the callback is returning a Comma Operator expression and the last operand's return value is what is returned. console..log is a void return, however, so undefined is returned as the map value. On top of the, .map returns an array, not an object, so there's no data property to destructure from the mapped array. Later accessing data.results is likely throwing a TypeError, something to effect of "cannot access 'results' of undefined".
Solution
If I understand your question correctly you have just created a local questionList JSON file that is imported and you are wanting to filter the results by some search criteria.
Example:
const [questions, setQuestions] = useState([]);
const fetchQuestions = (category = "", difficulty = "") => {
const data = questionList.results.filter(
(question) =>
question.category.toLowerCase().includes(category.toLowerCase()) &&
question.difficulty.toLowerCase().includes(difficulty.toLowerCase())
);
setQuestions(data);
};
useEffect(() => {
fetchQuestions();
}, []);
fetchQuestions(); - returns all 5 results
fetchQuestions("books"); - returns the 3 "books" category entries
fetchQuestions("", "easy"); - returns the 1 "easy" difficulty entry

Microsoft power automate: JSON "Object reference not set to an instance of an object"

I am attempting to create a JSON Object from an array to pass into a Microsoft product. The format in which the JSON object is accepted is shown beneath (content-type: "application/json"):
{
"value": [
{
"activityGroupNames": [],
"confidence": 0,
"description": "This is a canary indicator for demo purpose. Take no action on any observables set in this indicator.",
"expirationDateTime": "2019-03-01T21:44:03.1668987+00:00",
"externalId": "Test--8586509942423126760MS164-0",
"fileHashType": "sha256",
"fileHashValue": "b555c45c5b1b01304217e72118d6ca1b14b7013644a078273cea27bbdc1cf9d6",
"killChain": [],
"malwareFamilyNames": [],
"severity": 0,
"tags": [],
"targetProduct": "Azure Sentinel",
"threatType": "WatchList",
"tlpLevel": "green",
},
{
"activityGroupNames": [],
"confidence": 0,
"description": "This is a canary indicator for demo purpose. Take no action on any observables set in this indicator.",
"expirationDateTime": "2019-03-01T21:44:03.1748779+00:00",
"externalId": "Test--8586509942423126760MS164-1",
"fileHashType": "sha256",
"fileHashValue": "1796b433950990b28d6a22456c9d2b58ced1bdfcdf5f16f7e39d6b9bdca4213b",
"killChain": [],
"malwareFamilyNames": [],
"severity": 0,
"tags": [],
"targetProduct": "Azure Sentinel",
"threatType": "WatchList",
"tlpLevel": "green",
}
]
}
I making use of an inline code script in Microsoft automate that performs the following in JavaScript:
var threat = workflowContext.actions.Compose.outputs;
var value = Object.values(threat);
return value;
The workflowContext.actions.Compose.outputs line pulls an array consisting of objects shown in the following snippet:
[{"id": "1", "activityGroupNames": "test2"}, {"id": "2", "activityGroupNames": "test3"}, {"id": "3", "activityGroupNames": "test4"}]
This is my output:
{
"body": [
{
"id": "1",
"action": "alert",
"activityGroupNames": "test2"
},
{
"id": "2",
"action": "alert",
"activityGroupNames": "test3"
},
{
"id": "3",
"action": "alert",
"activityGroupNames": "test2"
}
]
}
it is pretty much identical to the format described my Microsoft shown in the first snippet. (https://learn.microsoft.com/en-us/graph/api/tiindicator-submittiindicators?view=graph-rest-beta&tabs=http) at the bottom.
I am unsure as to how I can change the key name from "body" to "value" and think maybe this will resolve my issue. Either way, I'd appreciate any other help on the matter, if any more context is required, please ask.
EDIT: The image beneath shows that the returned return value; is in fact being used as the input for a POST request to the Microsoft graph API

MongoDB aggregate function is not returning the value of collection joined using JavaScript

I needed assistance in order to work out why the aggregate function is not responding the way I'd expect it to respond. This is a RESTful API service I've designed in which I am trying to connect collections with each other. Please note the following:
Collection: Season
{
"_id": {
"$oid": "5c0fc60bfb6fc04dd6ea4e9a"
},
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81"
}
Collection: Play
{
"_id": {
"$oid": "5c0fc4aafb6fc04dd6ea4d81"
},
"Name": "It was the first time",
"Description": "One of the best action heros in the entertainment industry until this day",
"ReleaseDate": "24/12/2010",
"EndingDate": "12/08/2012",
"Category": "Drama"
}
My implemented code in JavaScript
function getTestLookUp(db, collectionName, response, secondCollectionName){
console.log('First collection name: ' + collectionName + '\n' + 'Second collection name: ' + secondCollectionName);
db.collection(collectionName).aggregate([
{
$lookup:
{
from: secondCollectionName,
localField: 'PlayID',
foreignField: '_id',
as: 'requestedDetails'
}
}
]).toArray((err, res) => {
if(err){
console.log(err);
} else {
console.log(res);
response.status(200).json({
'Items': res
});
}
});
}
The response
{
"Items": [
{
"_id": "5c0fc60bfb6fc04dd6ea4e9a",
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81",
"requestedDetails": []
}
]
}
The things I've checked so far: the collection names are accurate, the ID is also accurate as I can search it up on the MLabs search feature. I don't understand as to why this is returning a empty 'requestedDetails' as I hoped it would return the item from the Play collection.
In addition to this, I would also appreciate if someone can point out how I can join multiple collections instead of 2.
I welcome any questions regarding this problem.
While still researching for this issue, I accidentally came across a another problem in which someone wrote a comment stating that "you might be comparing a String with ObjectID". This was the cause for this error as I obtain a String variable in return from the database and I am comparing the String variable with the _id which is expecting to see a ObjectID variable to complete the query. Therefore, meaning that my query/lookup is never matching these two variables.
The only way tackle this issue is to do a conversion (string to ObjectID) and then compare the values. However, since I'm using the version of ^3.1.10 of MongoDB, this functionality is not possible. Will need to update the version to 4.0 to be able to implement this functionality.
In order to rectify this issue, I managed to surround the foreign ID within $iod tags.
Before
{
"_id": {
"$oid": "5c0fc60bfb6fc04dd6ea4e9a"
},
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81"
}
After
{
"_id": {
"$oid": "5c0fc60bfb6fc04dd6ea4e9a"
},
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": {
"$oid": "5c0fc4aafb6fc04dd6ea4d81"
}
}
Response
{
"Items": [
{
"_id": "5c0fc60bfb6fc04dd6ea4e9a",
"Season": "1",
"TotalEpisode": "15",
"Name": null,
"Description": "First season with no name for this drama",
"PlayID": "5c0fc4aafb6fc04dd6ea4d81",
"Details": [
{
"_id": "5c0fc4aafb6fc04dd6ea4d81",
"Name": "It was the first time",
"Description": "One of the best action heros in the entertainment industry until this day",
"ReleaseDate": "24/12/2010",
"EndingDate": "12/08/2012",
"Category": "Drama"
}
]
}
]
}

Differences with API's when trying to pull data

I am having difficulty with a pulling some data from an API for a school project using Jquery.
If I use the following coinmaketcap API I get the following response
https://api.coinmarketcap.com/v1/ticker/bitcoin/
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "8854.92",
"price_btc": "1.0",
"24h_volume_usd": "6759730000.0",
"market_cap_usd": "150480289107",
"available_supply": "16993975.0",
"total_supply": "16993975.0",
"max_supply": "21000000.0",
"percent_change_1h": "-0.13",
"percent_change_24h": "0.12",
"percent_change_7d": "8.3",
"last_updated": "1524459272"
}
]
I get am able to get the symbol for Bitcoin and place it into a variable by using this code
> $.getJSON('https://api.coinmarketcap.com/v1/ticker/btc/',
> function(data){
> var symbol = (data[0].symbol)
> })
Once I have it I can place it in a div.
However when I use cryptocompare API I don't get anything back
https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC,&tsym=USD
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD', function(data){
var symbol = (data[0].Internal)
});
This is the response -
{
"Message": "Success",
"Type": 100,
"Data": [
{
"CoinInfo": {
"Id": "1182",
"Name": "BTC",
"FullName": "Bitcoin",
"Internal": "BTC",
"ImageUrl": "/media/19633/btc.png",
"Url": "/coins/btc/overview",
"Algorithm": "SHA256",
"ProofType": "PoW",
"NetHashesPerSecond": 27483320229.3688,
"BlockNumber": 518932,
"BlockTime": 600,
"BlockReward": 12.5,
"Type": 1,
"DocumentType": "Webpagecoinp"
},
"ConversionInfo": {
"Conversion": "direct",
"ConversionSymbol": "",
"CurrencyFrom": "BTC",
"CurrencyTo": "USD",
"Market": "CCCAGG",
"Supply": 16986575,
"TotalVolume24H": 380849.0498955779,
"SubBase": "5~",
"SubsNeeded": [
"5~CCCAGG~BTC~USD"
],
"RAW": [
"5~CCCAGG~BTC~USD~4~8875.23~1524460635~0.00477012~42.152119404000004~231254719~10820.885574747872~96327075.76938197~66326.58563159907~593473019.8524572~8823.46~8917.05~8804.2~8864.31~9065~8780.91~Bitfinex~7ffe9"
]
}
}
]
}
Why is the second piece of code not working? Please help!
The second API is returning an object (in JSON format), not an array - see how the first character is { and how it has keys and values? You need to access the appropriate property to get the value you want. [0] notation indicates you're trying to access the first element of the array, but the outer object is not an array in this situation.
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD',
function(data){
var symbol = data.Data[0].CoinInfo.Internal;
});
In both the cases, we are getting data in different form. So, To get the 'BTC' in variable .
for 1st case -> symbol = data[0] ['symbol']
for 2nd case -> symbol = data['Data'][0]['CoinInfo']['Internal']
one is an [array of JSON] while other is an [object having key 'Data' with array value].

Categories