Filtering JSON in React - javascript

I'm loading some JSON data using FETCH. I'm trying to add/create a simple filtering functionality on the content displayed.
I'm getting this error:
Uncaught TypeError: Cannot read property 'toLowerCase' of undefined
Any idea what could be causing this error?
This my code so far:
let Table = React.createClass({
getInitialState: function(){
return {
accounts: [{
"product": "Fixed Saver",
"interestRate": 2.20,
"minimumDeposit": 500,
"interestType": "Fixed"
}],
searchString: ''
}
},
componentDidMount: function(){
fetch('http://localhost:8888/table/json/accounts.json')
.then(response => {
return response.json()
})
.then(json => {
this.setState({accounts: json})
});
},
handleChange: function(e){
this.setState({searchString:e.target.value});
},
render: function(){
var libraries,
libraries = this.state.accounts,
searchString = this.state.searchString.trim().toLowerCase();
if(searchString.length > 0){
libraries = libraries.filter(l => {
return l.name.toLowerCase().match( searchString );
});
}
return (
<div className="container">
<input type="text" value={this.state.searchString} onChange={this.handleChange} placeholder="Type here" />
<ul className="header clearfix">
<li>Product</li>
<li>Interest rate</li>
<li>Minimum deposit</li>
<li>Interest type</li>
</ul>
{libraries.map(l => {
return (
<div className="account clearfix" key={l.id}>
<div className="product">{l.product}</div>
<div>{l.interestRate} %</div>
<div>£ {l.minimumDeposit}</div>
<div>{l.interestType}</div>
</div>
)
})}
</div>
)
}
});
let App = React.createClass({
render: function(){
return(
<Table />
);
}
});
ReactDOM.render( <App />, document.getElementById('table') );
JSON
[
{
"id": 1,
"product": "Fixed Saver",
"interestRate": 2.20,
"minimumDeposit": 500,
"interestType": "Fixed"
},
{
"id": 2,
"product": "Fixed Saver",
"interestRate": 1.50,
"minimumDeposit": 0,
"interestType": "Tracker"
},
{
"id": 3,
"product": "Offset Saver",
"interestRate": 1.8,
"minimumDeposit": 1000,
"interestType": "Fixed"
}
]

Seem that you got the error from this line
libraries = libraries.filter(l => {
return l.name.toLowerCase().match( searchString );
});
Because of l.name is undefined. You can check again your JSON data. It doesn't have name attribute, seem that it is product.
You should not modify your state directly by: libraries = libraries.filter...
State should be updated by setState function.
In this case you should create temporary variable to display the results instead of directly use libraries variable.
I believe if your sample is worked, you only may search for the first time and next time the results will be only in your last search results, though.

Related

ReactJS Search input by multiple values

I have a search and select filters on my page. The issue that I am having is that I can't seem to make the search work with multiple json values.
Example value is { "id": "1", "role": "teacher", "subject": "mathematics", "name": "Jonathan Kovinski" } and I want to be able to use key and values.
I've tried using some other question about combining json key and value into a single array and passing it to the search filter but it didn't work.
text = data.filter(info => {
return Object.keys(info).map(function(key) {
var singleOne = JSON.stringify(info[key]);
console.log(info, "This is the json one")
}).toLowerCase().match(searchString);
});
Here is a link to a JS Fiddle that I've created with all of my code.
I am trying to set my search bar to use all keys and values for searching and sorting data.
i would suggest you put the filtered data in a seperate key in the state in case you want to revert to the original result,
use the Obeject.values instead of Object.keys and filter the data in the handleChange function,
here's a working code :
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: false,
data: [],
searchString: "",
filtered: []
};
this.handleChange = this.handleChange.bind(this);
}
componentDidMount() {
this.fetchData();
}
handleChange(e) {
var value = e.target.value;
this.setState({
searchString: value,
filtered: this.state.data.filter(e =>
Object.values(e)
.join(" ")
.toLowerCase()
.match(value)
)
});
}
fetchData() {
fetch("https://api.myjson.com/bins/lo3ls")
.then(response => response.json())
.then(json => {
this.setState({
isLoaded: true,
data: json,
filtered: json
});
})
.catch(error => console.log("parsing failed", error));
}
render() {
var { isLoaded, data } = this.state;
const searchString = this.state.searchString.trim().toLowerCase();
let text = this.state.data;
console.log(text);
if (searchString.length > 0) {
text = text.filter(info => {
return info.role.toLowerCase().match(searchString);
});
}
return (
<div>
<input
type="text"
id="searchbar"
value={this.state.searchString}
onChange={this.handleChange}
placeholder="Search"
name="device"
/>
<select className="category-select" name="categories" onChange={this.handleChange}>
{data.map(info => (
<option value={info.role}>{info.role}</option>
))}
</select>
{/* map through the filtered ones*/}
{this.state.filtered.map(info => (
<div className="display">
<span className="role">Role: {info.role}</span>
<span> Name: {info.name}</span>
<span>, Subject: {info.subject}</span>
</div>
))}
</div>
);
}
}
ReactDOM.render(<Hello name="World" />, document.getElementById("container"));
Actually, I read all of your code in Fiddle, But I proffer Fuse to you. Use it inside your code in componentDidMount and implement your search. it is very easy and handy.
const options = {
shouldSort: true,
threshold: 0.6,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
"title",
"author.firstName"
]
};
const fuse = new Fuse(list, options); // "list" is the item array
const result = fuse.search(""); // put your string inside double quotation
The result is your answer.

Getting server data with AJAX in React

I'm trying make an AJAX call to get server data into my React Components.
I'm unable to display it with React. I get this error:
Uncaught TypeError: Cannot read property 'map' of undefined
I've done research http://andrewhfarmer.com/react-ajax-best-practices/ and reactjs - Uncaught TypeError: Cannot read property 'map' of undefined ;however, I'm not sure how to map it to my react component.
Here is my code below:
var items;
$.get("http://localhost:3000/getProducts", function( data ) {
items = data;
this.state.items = data;
});
/*React Code Below */
var RepeatModule = React.createClass({
getInitialState: function() {
return { items: [] }
},
render: function() {
var listItems = this.props.items.map(function(item) {
return (
<div className='brick'>
<div>
<a target='_blank' href={item.productURL}><img src={item.imageURL}/></a>
<p className='itemName'>Short Sleeve Oxford Dress Shirt, White, Large</p>
<p className='storeName'>Nike Factory Store</p>
<img className='foundPicture' src='../images/rohit.png'/>
</div>
</div>
);
});
return (
<div>
{listItems}
</div>
);
}
});
ReactDOM.render(<RepeatModule items={items} />,
document.getElementById('clothing-content'));
My JSON array with item properties are valid:
Here is the array below:
[ { _id: 584d1e36a609b545b37611ac,
imageURL: 'http://ih1.redbubble.net/image.252113981.3904/ra,unisex_tshirt,x1350,fafafa:ca443f4786,front-c,30,60,940,730-bg,f8f8f8.u2.jpg',
productName: 'Drake',
productType: 'T-Shirts & Hoodies',
price: '$29.97',
productURL: 'http://www.redbubble.com/people/misfitapparel/works/22923904-drake?grid_pos=6&p=t-shirt',
__v: 0 } ]
Why is this error occurring? And how should it be implemented?
Javascript is asynchronous. Your get function callback does not block program flow, it executes at a later time. The rest of your code will continue to execute. You're sending an AJAX request asynchronously, then you're rendering a react component with an undefined variable. Then, at a later time, the get request will finish and your data will be populated, but this is long after rendering has completed.
The simplest solution here is to only render the component once your AJAX request has finished:
var RepeatModule = React.createClass({
render: function() {
var listItems = this.props.items.map(function(item) {
return (
<div className='brick'>
<div>
<a target='_blank' href={item.productURL}><img src={item.imageURL}/></a>
<p className='itemName'>Short Sleeve Oxford Dress Shirt, White, Large</p>
<p className='storeName'>Nike Factory Store</p>
<img className='foundPicture' src='../images/rohit.png'/>
</div>
</div>
);
});
return (
<div>
{listItems}
</div>
);
}
});
$.get("http://localhost:3000/getProducts", function( data ) {
ReactDOM.render(<RepeatModule items={data} />,
document.getElementById('clothing-content'));
});
A better solution, depending on your needs, is probably to do the AJAX request in a componentDidMount lifecycle method, and store the result in state instead of props.
var RepeatModule = React.createClass({
getInitialState: function() {
return { items: this.props.items || [] }
},
componentWillMount: function() {
console.log("componentWillMount()")
$.get("http://localhost:3000/getProducts", function( data ) {
this.setState({ items : data })
console.log(data,"data is here");
}.bind(this));
},
render: function() {
var listItems = this.state.items.map(function(item) {
return (
<ListItem item={item}/>
);
});
return (
<div>
{listItems}
</div>
);
}
});
/* make the items stateless */
var ListItem = function(props) {
return (
<div className='brick' key={props.item._id}>
<div>
<a target='_blank' href={props.item.productURL}><img src={props.item.imageURL}/></a>
<p className='itemName'>Short Sleeve Oxford Dress Shirt, White, Large</p>
<p className='storeName'>Nike Factory Store</p>
<img className='foundPicture' src='../images/rohit.png'/>
</div>
</div>
);
}
var data = []
ReactDOM.render(<RepeatModule items={data} />, document.getElementById('clothing-content'));
I had to bind the data and use componentWillMount.

React - send function props to Children

I saw some questions speaking about similar issues but somehow I still do not manage to solve my issue so here I am asking for your kind help. I am pretty new to React and would like to send a function from a Parent to a child and then use it from the Child but somehow when I want to use it it says
Uncaught TypeError: Cannot read property 'props' of undefined"
Edited Code after first answers were helping:
var Menu = React.createClass({
links : [
{key : 1, name : "help", click : this.props.changePageHelp}
],
render : function() {
var menuItem = this.links.map(function(link){
return (
<li key={link.key} className="menu-help menu-link" onClick={link.click}>{link.name}</li>
)
});
return (
<ul>
{menuItem}
</ul>
)
}
});
var Admin = React.createClass ({
_changePageHelp : function() {
console.log('help');
},
render : function () {
return (
<div>
<div id="menu-admin"><Menu changePageHelp={this._changePageHelp.bind(this)} /></div>
</div>
)
}
});
ReactDOM.render(<Admin />, document.getElementById('admin'));
Pass a value from Menu function and recieve it in the changePageHelp function and it works.
var Menu = React.createClass({
render : function() {
return (
<div>
{this.props.changePageHelp('Hello')}
</div>
)
}
});
var Admin = React.createClass ({
_changePageHelp : function(help) {
return help;
},
render : function () {
return (
<div>
<div id="menu-admin"><Menu changePageHelp={this._changePageHelp.bind(this)} /></div>
</div>
)
}
});
ReactDOM.render(<Admin />, document.getElementById('admin'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.14.8/react-dom.min.js"></script>
<div id="admin"></div>
For performance reasons, you should avoid using bind or arrow functions in JSX props. This is because a copy of the event handling function is created for every instance generated by the map() function. This is explained here: https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md
To avoid this you can pull the repeated section into its own component. Here is a demo: http://codepen.io/PiotrBerebecki/pen/EgvjmZ The console.log() call in your parent component receives now the name of the link. You could use it for example in React Router.
var Admin = React.createClass ({
_changePageHelp : function(name) {
console.log(name);
},
render : function () {
return (
<div>
<div id="menu-admin">
<Menu changePageHelp={this._changePageHelp} />
</div>
</div>
);
}
});
var Menu = React.createClass({
getDefaultProps: function() {
return {
links: [
{key: 1, name: 'help'},
{key: 2, name: 'about'},
{key: 3, name: 'contact'}
]
};
},
render: function() {
var menuItem = this.props.links.map((link) => {
return (
<MenuItem key={link.key}
name={link.name}
changePageHelp={this.props.changePageHelp}
className="menu-help menu-link" />
);
});
return (
<ul>
{menuItem}
</ul>
);
}
});
var MenuItem = React.createClass ({
handleClick: function() {
this.props.changePageHelp(this.props.name);
},
render : function () {
return (
<li onClick={this.handleClick}>
Click me to console log in Admin component <b>{this.props.name}</b>
</li>
);
}
});
ReactDOM.render(<Admin />, document.getElementById('admin'));

ReactJS not able to reference state created

http://jsfiddle.net/adamchenwei/3rt0930z/20/
I just trying to create an example to learn how state works in a list.
What I intent to do is to allow a particular value that got repeated in a list, to change, in ALL items in the list, by using state. For example, in this case, I want to change all the list item's name to 'lalala' when I run changeName of onClick.
However I have this warning (issue at fiddle version 11, resolved at version 15)
Any help on resolving it to achieve purpose above?
Actual Code
var items = [
{ name: 'Believe In Allah', link: 'https://www.quran.com' },
{ name: 'Prayer', link: 'https://www.quran.com' },
{ name: 'Zakat', link: 'https://www.quran.com' },
{ name: 'Fasting', link: 'https://www.quran.com' },
{ name: 'Hajj', link: 'https://www.quran.com' },
];
var ItemModule = React.createClass({
getInitialState: function() {
return { newName: this.props.name }
},
changeName() {
console.log('changed name');
this.setState({ newName: 'lalala' });
},
render() {
//<!-- <a className='button' href={this.props.link}>{this.props.name}</a> -->
return (
<li onClick={this.changeName}>
{this.state.newName}
</li>
);
}
});
var RepeatModule = React.createClass({
getInitialState: function() {
return { items: [] }
},
render: function() {
var listItems = this.props.items.map(function(item) {
return (
<div>
<ItemModule
key={item.name}
name={item.name} />
</div>
);
});
return (
<div className='pure-menu'>
<h3>Islam Pillars</h3>
<ul>
{listItems}
</ul>
</div>
);
}
});
ReactDOM.render(<RepeatModule items={items} />,
document.getElementById('react-content'));
-UPDATE-
fiddle version 16
updated fidle, now there is issue with key, also, the onClick did not update the value for all the list item. Is there something wrong I did?
-UPDATE-
fiddle version 20
Now the only issue is change all the list item's name to 'lalala' when I run changeName of onClick.
remove the parenthesis from
onClick={this.changeName()},
so
onClick={this.changeName}
you want to call the function onClick, but you are calling it on render that way
I think you meant to do onClick={this.changeName}
In the way you have it you are calling the changeName function on render instead of on click.

Passing keys to children in React.js

I am running through a react tutorial on tutsplus that is a bit old, and the code doesn't work as it was originally written. I actually am totally ok with this as it forces me to learn more independently, however I have spent a while on a bug that I just can't figure out. The bug consists of not being able to pass on an objects key, which prevents my program from updating the state of the correct object.
First off here is the repo if you want to run this code and see it in action: https://github.com/camerow/react-voteit
I have a child component that looks like this:
var FeedItem = React.createClass({
vote: function(newCount) {
console.log("Voting on: ", this.props, " which should have a key associated.");
this.props.onVote({
key: this.props.key,
title: this.props.title,
description: this.props.desc,
voteCount: newCount
});
},
voteUp: function() {
var count = parseInt(this.props.voteCount, 10);
var newCount = count + 1;
this.vote(newCount);
},
voteDown: function() {
var count = parseInt(this.props.voteCount, 10);
var newCount = count - 1;
this.vote(newCount);
},
render: function() {
var positiveNegativeClassName = this.props.voteCount >= 0 ?
'badge badge-success' :
'badge badge-danger';
return (
<li key={this.props.key} className="list-group-item">
<span className={positiveNegativeClassName}>{this.props.voteCount}</span>
<h4>{this.props.title}</h4>
<span>{this.props.desc}</span>
<span className="pull-right">
<button id="up" className="btn btn-sm btn-primary" onClick={this.voteUp}>↑</button>
<button id="down" className="btn btn-sm btn-primary" onClick={this.voteDown}>↓</button>
</span>
</li>
);
}
});
Now when someone hits the vote button the desired behavior is for the FeedItem.vote() method to send an object up to the main Feed component:
var FeedList = React.createClass({
render: function() {
var feedItems = this.props.items;
return (
<div className="container">
<ul className="list-group">
{feedItems.map(function(item) {
return <FeedItem key={item.key}
title={item.title}
desc={item.description}
voteCount={item.voteCount}
onVote={this.props.onVote} />
}.bind(this))}
</ul>
</div>
);
}
});
Which should pass that key on throught the parent component's onVote function:
var Feed = React.createClass({
getInitialState: function () {
var FEED_ITEMS = [
{
key: 1,
title: 'JavaScript is fun',
description: 'Lexical scoping FTW',
voteCount: 34
}, {
key: 2,
title: 'Realtime data!',
description: 'Firebase is cool',
voteCount: 49
}, {
key: 3,
title: 'Coffee makes you awake',
description: 'Drink responsibly',
voteCount: 15
}
];
return {
items: FEED_ITEMS,
formDisplayed: false
}
},
onToggleForm: function () {
this.setState({
formDisplayed: !this.state.formDisplayed
});
},
onNewItem: function (newItem) {
var newItems = this.state.items.concat([newItem]);
// console.log("Creating these items: ", newItems);
this.setState({
items: newItems,
formDisplayed: false,
key: this.state.items.length
});
},
onVote: function (newItem) {
// console.log(item);
var items = _.uniq(this.state.items);
var index = _.findIndex(items, function (feedItems) {
// Not getting the correct index.
console.log("Does ", feedItems.key, " === ", newItem.key, "?");
return feedItems.key === newItem.key;
});
var oldObj = items[index];
var newItems = _.pull(items, oldObj);
var newItems = this.state.items.concat([newItem]);
// newItems.push(item);
this.setState({
items: newItems
});
},
render: function () {
return (
<div>
<div className="container">
<ShowAddButton displayed={this.state.formDisplayed} onToggleForm={this.onToggleForm}/>
</div>
<FeedForm displayed={this.state.formDisplayed} onNewItem={this.onNewItem}/>
<br />
<br />
<FeedList items={this.state.items} onVote={this.onVote}/>
</div>
);
}
});
My logic relies on being able to reconcile the keys in the onVote function, however the key prop is not being properly passed on. So my question is, how do I pass on they key through this 'one way flow' to my parent component?
Note: Feel free to point out other problems or better design decision, or absolute stupidities. Or even that I'm asking the wrong question.
Looking forward to a nice exploration of this cool framework.
The key prop has a special meaning in React. It is not passed to the component as a prop, but is used by React to aid the reconciliation of collections. If you know d3, it works similar to the key function for selection.data(). It allows React to associate the elements of the previous tree with the elements of the next tree.
It's good that you have a key (and you need one if you pass an array of elements), but if you want to pass that value along to the component, you should another prop:
<FeedItem key={item.key} id={item.key} ... />
(and access this.props.id inside the component).

Categories