Not recognising this.state.data in ReactJs app - javascript

I am trying to build a simple Todo app, however throws an error:
Please can someone help identify the error??
Error
app.min.js:9 Uncaught TypeError: Cannot read property 'data' of undefined
at Object.value [as addNewContact] (http://localhost:8888/dist/assets/js/app.min.js:9:18059)
at b.value (http://localhost:8888/dist/assets/js/app.min.js:9:19043)
at Object.f.invokeGuardedCallback (http://localhost:8888/dist/assets/js/app.min.js:3:5790)
at g (http://localhost:8888/dist/assets/js/app.min.js:3:3021)
at Object.h [as executeDispatchesInOrder] (http://localhost:8888/dist/assets/js/app.min.js:3:3241)
at l (http://localhost:8888/dist/assets/js/app.min.js:2:30755)
at n (http://localhost:8888/dist/assets/js/app.min.js:2:30881)
at Array.forEach (native)
at c (http://localhost:8888/dist/assets/js/app.min.js:3:6210)
at Object.processEventQueue (http://localhost:8888/dist/assets/js/app.min.js:2:31947
Code:
import React from 'react';
import ReactDOM from 'react-dom';
export class ContactsListApp extends React.Component {
constructor(props) {
super(props);
this.state = {
data: this.props.data
}
}
addContact(newContactObj) {
console.log(newContactObj);
var tmpStateData = this.state.data;
tmpStateData.push(newContactObj.value);
this.setState({
data: tmpStateData
});
}
render() {
return (
<div className="contact-list">
<div className="container">
<div className="row">
<div className="col-xs-12 col-sm-12 col-md-12">
<AddContactPanel addNewContact={this.addContact} />
<ContactList contacts={this.state.data} />
</div>
</div>
</div>
</div>
)
}
}
class ContactList extends React.Component {
render() {
var items = Array.prototype.map.call(this.props.contacts, function (contact, index) {
return <ContactItem name={contact.name} key={index} />
});
return (
<ul>{items}</ul>
)
}
}
class AddContactPanel extends React.Component {
constructor(props) {
super(props);
}
handleAddContact() {
var contactItem = this.refs.newContactName;
this.props.addNewContact({
"_id": (Math.random(1000 * 10) + 1),
"name": this.refs.newContactName.value,
"occupation": "myJob",
"email": "me#hotmail.com",
"telephone": "0123456789"
});
}
render() {
return (
<div className="row">
<form>
<input required ref="newContactName" type="text" name="newContactName" />
<input type="submit" name="submit" onClick={this.handleAddContact.bind(this)} />
</form>
</div>
)
}
}
class ContactItem extends React.Component {
render() {
return (
<li>{this.props.name}</li>
)
}
}
module.exports = {
contactListApp: ContactsListApp
}
Thanks in advance!

First of all in order to make the state available to the function you need to bind it. You can make use of fat-arrow function for this purpose
addContact(newContactObj) {
console.log(newContactObj);
var tmpStateData = this.state.data;
tmpStateData.push(newContactObj.value);
this.setState({
data: tmpStateData
});
}
Secondly: setting props to the initial state is an anti-pattern as suggested by react docs and you should avoid using it this way. Instead you can set the state to a prop value in the componentDidMount function like
constructor(props) {
super(props);
this.state = {
data: ''
}
}
componentDidMount() {
this.setState({data: this.props.data})
}
addContact = (newContactObj) => {
console.log(newContactObj);
var tmpStateData = this.state.data;
tmpStateData.push(newContactObj.value);
this.setState({
data: tmpStateData
});
}

Related

React onClick event in array.map()

Edit: I have included the full code for better clarity
I am not sure if this is possible. I am trying to pass an onClick event via props but the click event does not work.
The parent component looks like this:
import React from 'react'
import { getProductsById } from '../api/get'
import Product from './Product'
import { instanceOf } from 'prop-types'
import { withCookies, Cookies } from 'react-cookie'
class Cart extends React.Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired
}
constructor(props) {
super(props)
const { cookies } = props;
this.state = {
prods: cookies.get('uircartprods') || '',
collapsed: true,
total: 0,
}
this.expand = this.expand.bind(this)
this.p = [];
}
componentDidMount() {
this.getCartProducts()
}
handleClick = (o) => {
this.p.push(o.id)
const { cookies } = this.props
cookies.set('uircartprods', this.p.toString(), { path: '/' , sameSite: true})
this.setState({prods: this.p })
console.log('click')
}
getCartProducts = async () => {
let products = []
if (this.state.prods !== '') {
const ts = this.state.prods.split(',')
for (var x = 0; x < ts.length; x++) {
var p = await getProductsById(ts[x])
var importedProducts = JSON.parse(p)
importedProducts.map(product => {
const prod = <Product key={product.id} product={product} handler={() => this.handleClick(product)} />
products.push(prod)
})
}
this.setState({products: products})
}
}
expand(event) {
this.setState({collapsed: !this.state.collapsed})
}
handleCheckout() {
console.log('checkout clicked')
}
render() {
return (
<div className={this.state.collapsed ? 'collapsed' : ''}>
<h6>Your cart</h6>
<p className={this.state.prods.length ? 'hidden' : ''}>Your cart is empty</p>
{this.state.products}
<h6>Total: {this.props.total}</h6>
<button onClick={this.handleCheckout} className={this.state.prods.length ? '' : 'hidden' }>Checkout</button>
<img src="./images/paypal.png" className="paypal" alt="Paypal" />
<a className="minify" onClick={this.expand} alt="My cart"></a>
<span className={this.state.prods.length ? 'pulse' : 'hidden'}>{this.state.prods.length}</span>
</div>
)
}
}
export default withCookies(Cart)
The Product component:
import React from 'react';
class Product extends React.Component {
constructor(props) {
super(props);
this.state = {
showDetails: false,
showModal: false,
cart: []
}
this.imgPath = './images/catalog/'
}
render() {
return (
<div className="Product">
<section>
<img src={this.imgPath + this.props.product.image} />
</section>
<section>
<div>
<h2>{this.props.product.title}</h2>
<h3>{this.props.product.artist}</h3>
<p>Product: {this.props.product.product_type}</p>
<h4>${this.props.product.price}</h4>
<button className="button"
id={this.props.product.id} onClick={this.props.handler}>Add to cart</button>
</div>
</section>
</div>
)
}
}
export default Product
If I log this.props.handler I get undefined. Everything works apart from the click handler, I was wondering if it might have something to with the async function. I am very new to React, there are still some concepts I'm not sure about, so any help is appreciated.
Okay, I see a few issues here.
First, there is no need to call this.handleClick = this.handleClick.bind(this) in the constructor, because you are using an arrow function. Arrow functions do not have a this context, and instead, accessing this inside your function will use the parent this found in the Class.
Secondly, it is wrong to store components in state. Instead, map your importedProducts inside the render function.
Thirdly, the issue with your handler is that this.props.handler doesn't actually call handleClick. You will notice in the definition handler={(product) => this.handleClick} it is returning the function to the caller, but not actually calling the function.
Try this instead.
class Product extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<button className="button" id={this.props.product.id} onClick={this.props.handler}>
Add to cart
</button>
</div>
);
}
}
export default Product;
import Product from './Product'
class Cart extends React.Component {
constructor(props) {
super(props);
}
handleClick = (o) => {
console.log('click');
};
render() {
return (
<div>
{importedProducts.map((product) => {
return <Product key={product.id} product={product} handler={() => this.handleClick(product)} />;
})}
</div>
);
}
}
export default Cart;

Pass input data from child to parent React.js

This may seem kind of basic but I'm just learning how to use React. Currently what I have going is when I type in the input field and submit, the system console logs my 'search' input. What I'm trying to do is pass my 'search' data from my child component to the parent. Looking for any tips or leads to the right direction.
This is what I have for my child component:
export default class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ''
};
}
onChange = event => {
this.setState({ search: event.target.value });
};
onSubmit = event => {
const { search } = this.state;
event.preventDefault();
console.log(search);
};
render() {
return (
<div className='search-bar'>
<form onSubmit={this.onSubmit}>
<input
className='search'
type='text'
placeholder='Search'
onChange={this.onChange}
search={this.props.search}
value={this.state.searchinput}
parentCallback={this.onChange}
></input>
</form>
<FontAwesomeIcon className='search-icon' icon={faSearch} />
</div>
);
}
}
And in my Parent component (nothing much at the moment)
export default class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ''
};
}
searchUpdate = search => {
console.log(search);
};
render() {
console.log(this.props.search);
return (
<div className='container'>
<SearchBar/>
</div>
);
}
}
Generally to pass data from child component to Parent Component, you can pass a reference of a function as props to child component from parent component and call that passed function from child component with data.
You can do something like this:
export default class SearchBar extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ''
};
}
onChange = event => {
this.setState({ search: event.target.value });
};
onSubmit = event => {
const { search } = this.state;
event.preventDefault();
console.log(search);
this.props.passSearchData(search);
};
render() {
return (
<div className='search-bar'>
<form onSubmit={this.onSubmit}>
<input
className='search'
type='text'
placeholder='Search'
onChange={this.onChange}
search={this.props.search}
value={this.state.searchinput}
parentCallback={this.onChange}
></input>
</form>
<FontAwesomeIcon className='search-icon' icon={faSearch} />
</div>
);
}
In parent component:
export default class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ''
};
}
searchUpdate = search => {
console.log(search);
this.setState({ ...state, search: search })
};
render() {
console.log(this.props.search);
return (
<div className='container'>
<SearchBar passSearchData={this.searchUpdate} />
</div>
);
}
The simplest way would be to pass a function from parent to child:
// in parent component
const setSearchValue = (search) => {
// setState to search
this.setState({search});
}
render (){
return <>
<SearchBar onsearch={this.setSearchValue} />
</>
}
// in child component
// change your searchUpdate
searchUpdate = () => {
const {onsearch} = this.state;
// function call to pass data to parent
this.props.onsearch(onsearch)
}
Just have a function that is passed as a prop to the child component. Let child component do the handle change part and pass the value back to the parent and then do whatever you want to with the value
Code sandbox: https://codesandbox.io/s/react-basic-example-vj3vl
Parent
import React from "react";
import Search from "./Search";
export default class Parent extends React.Component {
searchUpdate = search => {
console.log("in parent", search);
};
render() {
console.log(this.props.search);
return (
<div className="container">
<Search handleSearch={this.searchUpdate} />
</div>
);
}
}
Child
import React from "react";
export default class Search extends React.Component {
constructor(props) {
super(props);
this.state = {
search: ""
};
}
onChange = event => {
this.setState({ search: event.target.value }, () => {
console.log("in child", this.state.search);
this.props.handleSearch(this.state.search);
});
};
onSubmit = event => {
const { search } = this.state;
event.preventDefault();
console.log(search);
};
render() {
return (
<div className="search-bar">
<form onSubmit={this.onSubmit}>
<input
className="search"
type="text"
placeholder="Search"
onChange={this.onChange}
search={this.props.search}
value={this.state.searchinput}
/>
</form>
</div>
);
}
}

Where to fetch data in React component

I'm trying to get a feel for reactjs, new to front end development. Google Books API is simple so I decided to use it to build a react page that lists 10 books given the user input.
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
const GOOGLE_BOOKS_API = 'https://www.googleapis.com/books/v1/volumes?q=';
const GOOGLE_BOOKS_API_LIMIT = 'maxResults=10';
class BookItem extends React.Component {
render() {
return (
<div>
<img alt="Book" src={this.props.data.volumeInfo.imageLinks.thumbnail} />
<span>{this.props.data.volumeInfo.imageLinks.thumbnail}</span>
</div>
);
}
}
class BookResults extends React.Component {
render() {
const isBookResultsEmpty = !(this.props.books && this.props.books.length > 1);
const bookItems = isBookResultsEmpty ? [] : this.props.books.map((book,index) =>
<BookItem key={index} data={book} />
);
return (
<div className='book-results'>
{isBookResultsEmpty ? (
<h1>No Results</h1>
) : (
<div> {bookItems} </div>
)}
</div>
);
}
}
class BookSearch extends React.Component {
constructor(props) {
super(props);
this.state = {
bookQuery: '',
books: []
};
this.handleInputChange = this.handleInputChange.bind(this);
this.getBooks = this.getBooks.bind(this)
}
getBooks() {
let queryString = '';
if (this.state.bookQuery && this.state.bookQuery.length > 1) {
queryString = this.state.bookQuery.replace(/\s/g, '+');
fetch(`${GOOGLE_BOOKS_API}${queryString}&${GOOGLE_BOOKS_API_LIMIT}`)
.then(results => {
return results.json();
})
.then(json => {
this.setState({
books: json.items
});
})
.catch(e => console.log('error', e));
}
}
handleInputChange(event) {
this.setState({
bookQuery: this.search.value
},
this.getBooks());
}
render() {
return (
<div className="book-search">
<form>
<input
placeholder="Search for Books"
ref={input => this.search = input}
onChange={this.handleInputChange}
/>
</form>
<BookResults books={this.state.books} />
</div>
);
}
}
ReactDOM.render(<BookSearch />, document.getElementById('root'));
I get an error when typing the input:
TypeError: Cannot read property 'thumbnail' of undefined
I added a check for the data in the BookResults component but the error still occurs. I assume it has to do with the state or props value changing while rendering, but I don't know enough about React to be sure
Some books don't have imageLinks, so you need to make sure it is not undefined before you use it.
Example
class BookItem extends React.Component {
render() {
const { imageLinks } = this.props.data.volumeInfo;
if (!imageLinks) {
return null;
}
return (
<div>
<img alt="Book" src={imageLinks.thumbnail} />
<span>{imageLinks.thumbnail}</span>
</div>
);
}
}

ERROR: this.props.addNew is not a function

So I'm new to react and Ive been playing around with it for the past few weeks. I keep on getting this "ERROR: this.props.addNew is not a function" error about the addNew function within the addTheFriend function and I dont know why? Everything seems to correct to me. Can anybody help me? Thank you in advance.
import React, { Component } from 'react';
import { render } from 'react-dom';
export default class HelloUser extends React.Component {
constructor(props) {
super(props);
this.state = { name: "TT", friendsCount: 0 , friends: ["SS", "JJ", "Ww"] };
this.addFriends=this.addFriends.bind(this);
this.componentWillMount=this.componentWillMount.bind(this);
}
addFriends(friend) {
this.setState({
friends: this.state.friends.concat([friend]),
friendsCount: this.state.friendsCount + 1
});
}
componentWillMount() {
this.setState({
friendsCount: this.state.friends.length
});
}
render() {
return (
<div>
Villain: {this.state.name}, No of friends: {this.state.friendsCount}<br />
<AddingTheFriend addNew={this.addFriends} />
<ListFriends enemies={this.state.friends} />
</div>
);
}
};
export default class ListFriends extends React.Component {
render() {
var allFriends = this.props.enemies.map(function (friend) {
return <li>{friend}</li>;
});
return (
<div>
Her evil friends:
<ul>{allFriends}</ul>
</div>
);
}
};
export default class AddingTheFriend extends React.Component {
constructor(props) {
super(props);
this.state= {newFriend: ''};
this.updateNewFriend = this.updateNewFriend.bind(this);
this.addTheFriend = this.addTheFriend.bind(this);
}
updateNewFriend(change) {
this.setState({
newFriend: change.target.value
});
}
addTheFriend() {
this.props.addNew(this.state.newFriend);
this.setState({
newFriend: ''
})
}
render() {
return (
<div>
<input type="text" value={this.state.newFriend} onChange={this.updateNewFriend} />
<button type="button" onClick={this.addTheFriend}>Add Friend</button>
</div>
)
}
};
render(<HelloUser />, document.getElementById('root'));

React component not refresh after search active

i have an error in my react code, my result component is not changed after change array data, in console i just see new arrays after change input, new builded data is work, but component result isnot changed.
App.jsx
import React, { Component } from 'react'
import './App.css';
import fetch from 'isomorphic-fetch'
import Header from './Header'
import Content from './Content'
import Footer from './Footer'
class App extends Component {
constructor(props) {
super(props)
this.state = {
stripdata: null,
query: ""
}
this.query = this.query.bind(this)
}
componentWillMount() {
fetch(`http://localhost:3000/data/info.json`)
.then(results => results.json())
.then(data => {
this.setState({
stripdata: data
})
})
.catch(err => {
console.log("Didn't connect to API", err)
})
}
query(e) {
e = e.trim().toLowerCase();
this.setState({
query: e
})
}
show(data, query) {
return (query.length > 0) ?
data.filter(item => { return item.fakename.stripclub.toLowerCase().match( query ) }) :
data
}
render() {
console.log(this.show(this.state.stripdata, this.state.query))
return (
<div className="App">
<Header onQuery={this.query}/>
{
(this.state.stripdata === null) ?
<div className="loading">Loading data...</div> :
<Content onResult={ this.show(this.state.stripdata, this.state.query) }/>
}
<Footer />
</div>
);
}
}
export default App;
Content.jsx
import React, { Component } from 'react'
import Result from './Result'
class Content extends Component {
constructor(props) {
super(props);
this.state = {
stripdata: this.props.onResult
};
}
componentWillMount() {
}
render() {
return (
<div className="Content">
<Result stripdata={ this.state.stripdata }/>
</div>
);
}
}
export default Content;
Finder.jsx
import React, { Component } from 'react'
class Finder extends Component {
constructor(props) {
super(props)
this.state = {}
this.handleChange = this.handleChange.bind(this)
}
handleChange(e) {
this.props.find(e.target.value)
}
render() {
return (
<div className="Finder">
<form id="search" onSubmit="">
<span>i want</span>
<input type="text"
placeholder="type who you want"
onChange={ this.handleChange }
/>
</form>
</div>
);
}
}
export default Finder;
Header.jsx
import React, { Component } from 'react'
import Finder from './Finder'
class Header extends Component {
constructor(props) {
super(props);
this.state = {
};
this.find = this.find.bind(this);
}
find(e) {
this.props.onQuery(e)
}
render() {
return (
<div className="Header">
<div className="inner">
<h2>Find with which girl you want to spend your time !!!</h2>
<Finder find={ this.find }/>
</div>
</div>
);
}
}
export default Header;
Result.jsx
import React, { Component } from 'react'
import PersonCard from './PersonCard'
class Result extends Component {
constructor(props) {
super(props);
this.state = {
stripdata: this.props.stripdata
};
}
componentWillMount() {
}
render() {
return (
<div className="result">
{
this.state.stripdata.map((item, i) => {
return <PersonCard key={i} data={item}/>
})
}
</div>
);
}
}
export default Result;
import React, { Component } from 'react'
import Facebook from 'react-icons/lib/fa/facebook'
import VK from 'react-icons/lib/fa/vk'
import Phone from 'react-icons/lib/fa/phone'
PersonCard.jsx
class PersonCard extends Component {
constructor(props) {
super(props);
this.state = {
info: this.props.data
};
}
render() {
var now = new Date().getFullYear();
return (
<div className="PersonCard">
<div className="layer one">
<div className="side left face-image">
<img src={(this.state.info.photo) ? this.state.info.photo : ""} alt="Person Pic" />
</div>
<div className="side right info">
<p><b>Fake Name:</b> { this.state.info.fakename.stripclub }</p>
<p><b>Real Name:</b> { (this.state.info.name) ? this.state.info.name : null }</p>
<p><b>Currently Workplace:</b> { (this.state.info.address.work ) ? this.state.info.address.work : null }</p>
<p><b>Age:</b> { (this.state.info.born) ? (now - this.state.info.born.slice(0, 4)) : null }</p>
<p><br /><a href={ (this.state.info.fakename.facebook) ? this.state.info.fakename.facebook.id : null } ><icon><Facebook /></icon> { (this.state.info.fakename.facebook) ? this.state.info.fakename.facebook.user : null }</a></p>
<p><br /><a href={ (this.state.info.fakename.vk) ? this.state.info.fakename.vk.id : null }><icon><VK /></icon> { (this.state.info.fakename.vk) ? this.state.info.fakename.vk.user : null }</a></p>
<p><br /><a href={ (this.state.info.phone) ? "tel:" + this.state.info.phone : null }><icon><Phone /></icon> { (this.state.info.phone) ? this.state.info.phone : null }</a></p>
</div>
</div>
<div className="layer two">
<div className="about">
<p>{ this.state.info.physical }</p>
<p>{ (this.state.info.work_days) ? 'All Week ' + this.state.info.work_days : null }</p>
</div>
</div>
</div>
);
}
}
export default PersonCard;
Please help me with with this issue.
Try to write the Content component like this:
class Content extends Component {
render() {
return (
<div className="Content">
<Result stripdata={ this.props.onResult }/>
</div>
);
}
}
And the Result component like this also:
class Result extends Component {
render() {
return (
<div className="result">
{
this.props.stripdata.map((item, i) => {
return <PersonCard key={i} data={item}/>
})
}
</div>
);
}
}
And in the PersonCard replace every reference of this.state to this.props and remove the assignment in the constructor.
I am guessing the problem is with the assignments of props into state like in the Content component:
constructor(props) {
super(props);
this.state = {
stripdata: this.props.onResult
};
}
the constructor is probably not getting called after the input values changes.
The assumption that the constructor is getting called every time the component is rendered confuses a lot of beginner react devs...
Anyway you dont need to use state in these presentational components (https://medium.com/#dan_abramov/smart-and-dumb-components-7ca2f9a7c7d0)
just use props.

Categories

Resources