Cannot display the data from a JSON file in React - arrays

I'm trying to display the data from my local JSON file in React. Here is how I see the data from the console: JSON data in the console. The structure is Data -> Classes -> Class[0-730] -> Term (or any other).
So if I try to print the Term of Class[0] in the console, I would do
console.log(Data.Classes.Class[0].Term)
and get the desired result. However, when I try to display the same data in the website, I get the following error:
Cannot read property '0' of undefined
Here is how my code looks like:
return Data.Classes ? (
<ul>
{Object.keys(Data.Classes).map((item, idx) => {
return item ? (
<li key={idx}>
<h3>{item.Class[idx] ? item.Class[idx] : "Doesn't exist"}</h3>
</li>
) : null;
})}
</ul>
): null;
};
I assume there is something going wrong after mapping that makes item.Class[idx] undefined, but I am not sure why. Is there something I am missing?

idx is the index of the item, so it doesn't make sense to use the index of the parent item lower in the depth.
Since you're called the map on Object.keys(Data.Classes), you're mapping the keys from a list of strings, so it will look like this: ["key1", "key2"..].
As I see it, you likely want this:
{Data.Classes.Class.map((item, idx) => {
return (
<li key={idx}>
<h3>{item.Term} - {item.Dept} - {item.Course} - {item.Section}</h3>
</li>
);
})}
I'm not sure why you have ternary operators. Specific keys might be null, but Map will only go to items on the list, so item will never be null. It might be empty (like {} or '') but not null.

Related

Highlighting a substring in a string

I'm trying to highlight a matched substring in a searchable array of strings. I'm pretty close I think, just that last bit is not working.
I display an array of strings. When I type in an input the substrings in the array are supposed to get highlighted (using <mark></mark>) when matched with the input. The matching works ok but instead of highlighted text I get [object Object] instead.
So this is the part of code in question (it sits in Jsx inside a .map() method:
<div>
{item.matched.length > 0
? item.name.replace(new RegExp(inputText, 'gi'), (match) => (
<mark>{match}</mark>
))
: item.name}
</div>
The item is an element of the array that I'm mapping and has two properties: name & matched. matched is either empty or contains the typed search pattern if part or all of name matches it.
And this is what I'm getting when typing into text box:
So clearly the search and match work correctly and look what I get: [object Object] instead of highlighted search pattern.
I've tried to return a template string, like that backquote<mark>${match}</mark>backquote, but that results in displaying <mark>a</mark> in my example.
So I'm at loss here and any constructive feedback will be greatly appreciated.
we should render at in html
<div dangerouslySetInnerHTML={{ __html: (item.matched.length > 0
? item.name.replace(new RegExp(inputText, 'gi'), (match) => {
return `<span>${match}</span>`
})
: item.name) }}>

React Map within a map

I am having trouble to have a map within a map.
As you can see below I have commented several tries, ideally I wanted to use workItem.bullets.map((bulletItem, i)=><li key={i}>{bulletItem}</li>)
directly.
If I use it directly I will have "Cannot read properties of undefined (reading 'map')".
On this version I will get a undefined is not iterable (cannot read property Symbol(Symbol.iterator)) even though console.log seems to work fine and shows the type as Array as expected. The Array.from is useless but I since I am not understanding what's happening I gave it a try.
const work = this.props.data.work.map( workItem => {
console.log(workItem.bullets);
//let bulletPts = workItem.bullets.map((bulletItem, i)=><li key={i}>{bulletItem}</li>);
//let bps = workItem.bullets.map((bulletItem, i)=>"toto");
let array = Array.from(workItem.bullets);
return (
<div key={workItem.company}>
<h3>{workItem.company}</h3>
<p className="info">
{workItem.title}
<span>•</span> <em className="date">{workItem.years}</em>
</p>
<p>{workItem.description}</p>
<ul>
{
array.map(bulletItem => "test")
}
</ul>
</div>
);
});
I also took a look at How to map inside a map function in reactjs as it looked like a similar problem but I was not able to apply it to my issue.
I don't think it is needed but If you want to see the full project I am trying to add bullet points for resume, resumeData.json needs to be modified to contain some bulletPoints.
https://github.com/nordicgiant2/react-nice-resume
There is somethign wrong with your JSON :D

Cannot read property 'includes' of undefined when trying to aply a filter based on a user's input

Im trying to aplly tis simple filter ased on a query of a list that with each input the list will narrow the possibilities
HTML:
<mat-form-field>
<mat-label>Search for users</mat-label>
<input #query type="text" matInput placeholder="search" (keyup)="filter(query.value)">
</mat-form-field>
<div *ngIf="filteredUsers">
And the function:
filter(query){
this.filteredUsers= query?
this.users.filter(user=>user.username.includes(query)):
this.users;
}
<ul *ngFor="let u of filteredUsers">
<li>
{{u.username}}
</li>
</ul>
</div>
The error I get as I input a character id that filter is undefined, but since both arrays fileterdUsers and Users are populated, I can't understand why this error is beig thrown...Any ideas?
EDIT: the ngOninit:
ngOnInit(): void {
this.dataService.getUsers()
.pipe(first())
.subscribe(users=>{
this.filteredUsers=this.users=users;
console.log(users, this.filteredUsers) -> i get the data
})
}
Edit 2 :
EDIT
filter(query){
console.log(this.users)
this.filteredUsers= query?
this.users.filter(user=>user.username.includes(query)):
this.users;
console.log(this.users)
}
Like this I don't see any logs...
EDIT 3: snapshot
Ok, maybe I have an idea of whats going on. The first elements of my ngFor are empty as you can see in the picture. Is this the reason for Angular's complaint? (your last fix didn't solve the issue as well)
If console.log doesnt log your array, it means its empty at the time filter(query) is being called. And I just noticed the way you are assigning the array isnt really what you want since arrays work by reference.
ngOnInit(): void {
this.dataService.getUsers()
.pipe(first())
.subscribe(users=>{
this.filteredUsers=users;
this.users=users; //just to be sure
console.log(users, this.filteredUsers) -> i get the data
})
}
filter returns an array so I guess you want to assign that to the filteredUser. I removed the code that made no sense.
filter(query){
console.log(this.users)
this.filteredUsers = query ? this.users.filter(user=> user.username && user.username.includes(query)): this.users
console.log(this.filteredUsers)
}
Whith the help and envolvment of #ukn I found the solution: the first elements of the array - seen on pic - , in this case users, were empty, so the solution was deleting those elements. The filter function is now working properly, giving me the names as I input a single char. The list gets updated trying to match the chars I input.

React JSX mapping through data where sometimes a data field is missing

im looping through data
This is react.js / jsx
If I am pulling 100 items, none will show because of one being undefined. I just want it to display "0" if it is undefined, and show the size if it is there.
Error: Cannot read property size of undefined.
Example of data,
Item={
color:blue,
size:medium,
}
Item={
color:red
}
I am mapping through the data.
Im essentially doing this :
return items.map((item, i) => {
return( {item.size})
I have also tried {item.size ? "itWorks" : "0"} as a test, and I get the same error.
It is better to use object.hasOwnProperty('property') to check whether your object has a particular property or not . for your case it is:
{item.hasOwnProperty('size') ? "itWorks" : "0"}
The error is:
Error: Cannot read property size of undefined
It means item is undefined,
So you gotta check for item and item.size.
You should do,
return (
items && items.map(function(item, id){
.....}))
So the loop goes through when items array is of some length otherwise it exits

Firebase Key/Value access not working

I have the following data setup in firebase.
{
"data": {
"lava14mod1":"down",
"lava14mod2":"up"
}
}
I'm able to access it in my React app. But I can only access it as a (key,value) pair combined as one string.
I cannot access the key or value separately using,
<li>{this.state.data[0]['.key']}</li>
I'm getting this error,
Uncaught TypeError: Cannot read property '.key' of undefined
Uncaught TypeError: Cannot read property '_currentElement' of null
Here's the full code, running on plunker, (without the error line)
http://plnkr.co/edit/zjFKsYAzfYrzGmedVEV6?p=preview
I've been pouring through the docs and still can't figure this out. I'm following the data structure shown in firebase docs,
[
{
".key": "-Jtjl482BaXBCI7brMT8",
".value": 100
},
{
".key": "-Jtjl6tmqjNeAnQvyD4l",
"first": "Fred"
"last": "Flintstone"
},
{
".key": "-JtjlAXoQ3VAoNiJcka9",
".value": "foo"
}
]
Firebase documentation
Is there some problem with my syntax? How do I access the key or value separately?
Thank you so much.
You're getting that error because the this.state.data object does not have the keys you're trying to access in render.
This is easy to see if you simply put a console.log(this.state.data) in render. Doing so gives me something like this in the console:
> []
> [Object]
> [Object, Object]
> [Object, Object, Object]
So, render is being called four different times, once each time that this.state.data is being updated with a new key. But, in your render, you don't consider the fact that keys [0] and [1] might not exist - you try to access them without checking them first.
Now I'm not sure exactly why your state is being updated piecemeal, but it probably has something to do with the ReactFireMixin which I have no experience with. Fetching form Firebase is clearly an asynchronous action (since you have to grab data from the cloud) so you need to make accommodations for that.
The most straightforward fix is simply checking to make sure that the key you want to access actually exists on an object before you try to access it (which is a good practice in most cases to avoid exactly this kind of error!)
render: function() {
return (
<div>
from firebase,
{this.state.data ? <li>{this.state.data}</li> : undefined}
{this.state.data && this.state.data[0] && this.state.data[0][".key"] ? <li>{this.state.data[0][".key"]}</li> : undefined}
{this.state.data && this.state.data[1] && this.state.data[1][".key"] ? <li>{this.state.data[1][".key"]}</li> : undefined}
local var,
<li>{data2[0]['.key']}</li>
</div>
);
}
http://plnkr.co/edit/7XXaOIQCQcyGneqEqa88?p=preview
An even better solution would be to use Array.map to convert whatever array this.state.data is at the time directly into some kind of list. This is a very common pattern in React applications because you'll often keep lists of data as arrays and then want to display it dynamically.
render: function() {
return (
<div>
from firebase,
{this.state.data.map(function(ea){return <li>Key: <strong>{ea[".key"]}</strong>, Value: <strong>{ea[".value"]}</strong></li>})}
local var,
<li>{data2[0]['.key']}</li>
</div>
);
}
http://plnkr.co/edit/b1j10M1i635hvapFxZbG?p=preview
More about Array.map()

Resources