Why am I getting ,, Cannot read property 'load' of undefined" - reactjs

I have defined cookie in my project like this.
import cookie from 'react-cookie'. So that means I have defined cookie so I shouldn't be getting that error but sitll I am getting it.. I will share my code if anyone thinks it's needed.
EDIT
I om only adding here half of the code since I have to add some more details with the full code And I have no I idea what to add. The full code can be found here https://pastebin.com/APTdX879
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Block from "./Block"
import Add from './Add'
import cookie from 'react-cookie'
class App extends Component {
constructor(props){
super(props)
this.state = {
logedin: cookie.load("logedin")
}
}
submit(){
fetch("/newaccount")
.then(res=>res.json())
.then(data=>{
console.log(data)
console.log(document.getElementById('username').value)
let arr = data.filter(event=>{
return (event.username==document.getElementById('username').value&&event.password==document.getElementById('password').value)
})
console.log(arr.length)
console.log(arr)
if(arr.length==1){
this.setState({logedin:true})
}
else{
alert("wrong useranme or password")
}
})
}
componentDidMount(){
fetch("/api")
.then(response=>response.json())
.then(data=> this.setState({data: data}))
.catch(error=>console.log(error+' 1'))
}
componentWillMount() {
}
render() {
if(!this.state.logedin){
return (
<div>
<input id="username"/>
<input id='password' type="password"/>
<button onClick={this.submit.bind(this)}>Submit</button>
</div>
)
}
if(!this.state.data){
return <p>loading</p>
}
return (
<div>
<hr/>
<Add/>
{
this.state.data.map((data,i)=>{
return(
<div key={i+"a"}>
<Block name={data.username} img={data.img} date={data.date} text={data.text} likes={data.likes} comments={data.comments} key={i} id={data._id}></Block>
<br key={i+"b"}/>
</div>
)
})
}
</div>
*Second EDIT here is a screenshot of the error http://prntscr.com/gghb5p .

According to the react-cookie documentation at https://www.npmjs.com/package/react-cookie you should import it like this:
import { CookiesProvider, withCookies, Cookies } from 'react-cookie';
And then getting a cookie in the constructor won't work, you will need to do it in the componentWillMount() method like this:
componentWillMount() {
const { cookies } = this.props;
this.state = {
name: cookies.get('name') || 'Ben'
};
}

try to inject it first:
import { withCookies } from 'react-cookie';
export default withCookies(App);
or
App = withCookies(App);
and then in your constructor:
this.state = {
logedin: props.cookies.get("logedin")
}
EDIT: in documentation of react-cookie there is no load method, I think you need
logedin: props.cookies.get("logedin")

Related

Having trouble rendering data in react component

I'm trying to render the following the 'dogName' value of the following array to the browser, but it's coming up as 'undefined':
[
{
"id": 1,
"dogName": "bruce"
},
{
"id": 2,
"dogName": "borker"
},
{
"id": 3,
"dogName": "henry"
}
]
So, first of all, the data is pulled from a database and set in state in the parent component, where's it's passed as props to the child component 'DogNameList' (which I've trimmed down to just the relevant bits):
import React from 'react';
import './styles.css'
import DogList from './DogList'
import Dogue from './Dogue'
import axios from 'axios'
import DogNameList from './DogNameList'
class App extends React.Component {
constructor(){
super()
this.state = {
**dogName:[]**
}
}
componentDidMount() {
axios.get('http://localhost:3000/dogs')
.then(res => {
this.setState({
**dogName:res.data**
})
})
.catch(error => {
console.log(error)
})
}
render() {
return (
<div>
<DogNameList **names = {this.state.dogName}**/>
<Dogue/>
</div>
);
}
}
export default App;
In DogNameList, the data is mapped over and then passed as props to the 'Dogue' component (stupid names, I know, but this is a personal project):
import React from 'react'
import Dogue from './Dogue'
const DogNameList = (props) => {
return(
<div>
{
props.names.map(name => {
console.log(name.dogName)
return <Dogue name = {name} key ={name.id}/>
})
}
</div>
)
}
export default DogNameList
finally, it's supposed to be rendered to the browser via the 'Dogue' component:
import React from 'react'
import axios from 'axios'
class Dogue extends React.Component {
constructor(props){
super(props)
this.state = {
}
}
render(){
return (
<div>
<img className = 'img' src = {this.props.dogList}/>
<br/>
<form className = 'form'>
<input type = 'text' placeholder = 'Enter dog name'/>
<br/>
<button>Submit</button>
</form>
**<h2>dog name: {this.props.name}</h2>**
</div>
)
}
}
export default Dogue
Any ideas why it's not working? I console logged the following and it returned the list of names (not as strings, I should add):
props.names.map(name => {
console.log(name.dogName)
First of all, replace this
<h2>dog name: {this.props.name}</h2>
with this
<h2>dog name: {this.props.name.dogName}</h2>
because you are creating a component with object, so name property actually holds the object, not the name property of the object.
return <Dogue name = {name} key ={name.id}/>
You also don't declare somewhere this property
{this.props.dogList}
Also to handle the undefined error messages, do this
{this.state.dogName && <DogNameList names ={this.state.dogName}/>}

Accessing variable from imported class from another React script

I'm importing a class from another script in my main React App, and would like to access a variable within that class from the main App. Basically the user types something into a textbox, then clicks a button to add that value to a variable. In the main App I import that class, then have another button to print those values (selectedvalues). I'm not entirely sure how to do it, but this is my code so far:
Class I am importing:
import React, { Component } from 'react';
class MyModule extends Component {
constructor() {
super();
this.state = {
selectedValues: '',
}
}
addValue() {
this.selectedValues += document.getElementById('textBox1').value + ', '
return this.selectedValues
}
render() {
return(
<div>
<input type='text' id='textBox1' />
<button onClick={() => this.addValue()}>Add Value</button>
</div>
)
}
}
export default MyModule
And where I would like to actually access that value
import React, { Component } from 'react';
import MyModule from './myModule.js'
class App extends Component {
constructor() {
super();
this.state = {
}
}
printValues() {
console.log(document.getElementById('themodule').selectedvalues)
}
render() {
return(
<MyModule id='themodule' />
<button onClick={() => printValues()}>Print values</button>
)
}
}
export default App
Is there a way I can do this?
Thanks!
Edit JS-fiddle here https://jsfiddle.net/xzehg1by/9/
You can create Refs and access state and methods from it. Something like this.
constructor() {
this.myRef = React.createRef();
}
render() { ... <MyModule id='themodule' ref={this.myRef} /> }
printValues() {
console.log(this.myRef)
}
more info here https://reactjs.org/docs/refs-and-the-dom.html
Basically, your state (selectedValues) has to go one level up in the React tree. You have to declare it as App's state, and then pass it down to MyModule via props.
Btw in addValue(), you're not changing any state. And this.selectedValues will be undefined. It's this.state.selectedValues, and this.props.selectedValues once you correct your code.
I think you should first read all react concepts and then start working on it. Anyhow i am modifying your code in one way to get your desired functionality but remember this is not best practice you have to use Redux for this kind of features
import React, { Component } from 'react';
class MyModule extends Component {
constructor() {
super(props);
this.state = {
inputValue : ''
};
this.handleInput = this.handleInput.bind(this);
this.addValue = this.addValue.bind(this)
}
handleInput(e){
this.setState({
inputValue : e.target.value
})
}
addValue() {
this.props.addValue(this.state.inputValue);
}
render() {
return(
<div>
<input type='text' id='textBox1' onChange={handleInput} />
<button onClick={this.addValue}>Add Value</button>
</div>
)
}
}
export default MyModule
and your main component should be
import React, { Component } from 'react';
import MyModule from './myModule.js'
class App extends Component {
constructor() {
super(props);
this.state = {
selectedValues : ''
};
this.printValues = this.printValues.bind(this);
this.addValues = this.addValues.bind(this);
}
printValues() {
console.log(this.state.selectedValues);
}
addValues(val){
this.setState({
selectedValues : this.state.selectedValues + " , "+val
})
}
render() {
return(
<React.Fragment>
<MyModule addValue={this.addValues}/>
<button onClick={this.printValues} >Print values</button>
</React.Fragment>
)
}
}
export default App
This should do your work

I face this export error of Cookie using in react

I do have this code and I'm going to use Cookies for first time but I get error below , anyone who can help me to fix the problem ?
"ERROR I FACE : Attempted import error: 'react-cookie' does not contain a default export (imported as 'Cookie'). "
import React from 'react';
import ReactDom from 'react-dom';
import './App.css';
import CountDown from './CountDown';
import Basket from './Basket';
import Cookie from 'react-cookie'
class Products extends React.Component{
constructor(props){
super(props);
this.state={
order : []
}
this.shop = this.shop.bind(this);
}
prevstate = [];
`enter code here`shop(evt){
this.prevstate.push(evt.target.id);
this.setState({
order : this.prevstate
})
console.log(Cookie.get('selected'))
Cookie.set('selected' , this.props.cart , {path :' /'});
}
render(){
return(
<div className="prowrap">
{this.props.prolist.map((name) => (
<div className="pro" key={name.id} style={{border:"1px red
solid"}} >
<img src={name.image}/>
<p>{name.name}</p>
<p>{name.detail}</p>
<p className="countdown"><CountDown time={name.date}/></p>
<div className="price">{name.price} Euro</div>
<button className="shop" id={name.id} onClick={this.shop}>Add To
Cart</button>
</div>))}
<Basket cart={this.state.order} allpro={this.props.prolist}/>
</div>
)
}
}
export default Products;
The error is clear react-cookie doesn’t have default export so you cannot import it like
import Cookie from 'react-cookie';
You need to import it like below
import { Cookies } from 'react-cookie';
Also it's not Cookie but Cookies. You are importing it wrongly
When it is default export then you don’t use {} to import but if it is not default export then you use {} to import it.
You need to import like import { withCookies, Cookies } from 'react-cookie'; and then cookies.get('selected'), refer the code below
Read the package readme carefully.
// App.jsx
import React, { Component } from 'react';
import { instanceOf } from 'prop-types';
import { withCookies, Cookies } from 'react-cookie';
import NameForm from './NameForm';
class App extends Component {
static propTypes = {
cookies: instanceOf(Cookies).isRequired
};
constructor(props) {
super(props);
const { cookies } = props;
this.state = {
name: cookies.get('name') || 'Ben'
};
}
handleNameChange(name) {
const { cookies } = this.props;
cookies.set('name', name, { path: '/' });
this.setState({ name });
}
render() {
const { name } = this.state;
return (
<div>
<NameForm name={name} onChange={this.handleNameChange.bind(this)} />
{this.state.name && <h1>Hello {this.state.name}!</h1>}
</div>
);
}
}
export default withCookies(App);

React componentDidMount does not show axios response

I have React component RandomQouteMachine which is supposed to get response from the provided URL and display it on the page. I don't see response displayed. The debug 'Did component mount ?' message is missing too..
import React, { Component } from 'react';
import axios from 'axios';
lass RandomQouteMachine extends Component {
constructor(props) {
super(props);
this.state = {
data: ""
};
}
componenetDidMount() {
console.log('Did component mount ?');
axios.get('https://api.icndb.com/jokes/random')
.then((res) => {
this.setState({data:res.value.joke});
})
}
render() {
return (
<div>
Here it is:
{this.state.data}
</div>
);
}
}
export default RandomQouteMachine;
Am I using componenetDidMount() correctly ? I can see only 'Here it is:' displayed on page
check your spelling.
componenetDidMount !== componentDidMount

Cannot read property 'map' of undefined in ReactJS

I've got a problem with my ReactJS App with getting data from api. I still have an error: 'Cannot read property 'map' of undefined', and I have no idea why it's happening.
My code:
UsersList.js
import React from 'react';
import ReactDOM from 'react-dom';
import fetch from 'isomorphic-fetch';
import { Card, Container, Icon } from 'semantic-ui-react'
import User from './User'
class ProfilesList extends React.Component {
constructor(props) {
super(props);
this.state = {
users: [],
fetched: false,
loading: false,
};
}
componentWillMount(){
this.setState({
loading : true
});
fetch('http://58be98154389c312007f403f.mockapi.io/users/users').then(res => res.json())
.then(res =>{
this.setState({
users : res.results,
loading : true,
fetched : true
});
});
}
render() {
const {fetched, loading, users} = this.state;
let content;
if(fetched){
content = <div>{this.state.users.map((user,index) =>
<User key={user.username} id={index+1} user={user}/>)}</div>;
}
else if(loading && !fetched){
content = <p> Loading ...</p>;
}
else{
content = (<div></div>);
}
return (
<div>
{content}
</div>
);
}
}
export default ProfilesList;
User.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Card, Container, Icon } from 'semantic-ui-react'
class User extends React.Component {
render() {
const {user, id} = this.props;
return (
<Card
image='http://semantic-ui.com/images/avatar/large/elliot.jpg'
header={user.username}
meta='Friend'
description='Elliot is a sound engineer living in Nashville who enjoys playing guitar and hanging with his cat.'
extra={(
<a>
<Icon name='user' />
16 Friends
</a>
)}
/>
);
}
}
export default User;
Thanks for your help!
Your state.users is undefined when you try to do this.state.users.map() in your render function. So task #1 is to figure out why your fetch() is returning undefined and fix that. It's a good idea to build in some handling for cases when you get undefined results or other errors and set your state appropriately. Additionally, I tend to check that an expected array is not undefined before I try to map it, like this:
{
expectedArray
?
expectedArray.map(someMappingFunction)
:
<div>expectedArray was 'undefined' or otherwise 'falsy'</div>
}
Such a conditional statement is called a "ternary" and is very useful because it can be embedded in JSX as an "if/else" statement. It has the form (condition) ? (expression if true) : (expression if false). For example:
var foo = 7;
var bar = (foo % 2 == 0) ? "Even" : "Odd";
console.log(bar); // "Odd"

Resources