I am attempting to use setState in React - reactjs

I'm attempting to use setState function to a method in my App class..
example of the current code:
addRandomContact() {
this.setState({
actors: contacts.slice(0, 6)
})
}
I am expecting my contacts array to change from a length of 5 to 6.
The error I am receiving is the following:
TypeError: Cannot read property 'setState' of undefined
addRandomContact

"this" keyword will not be accessible inside this function and hence its undefined.
You have to use arrow function like below:
addRandomContact = () => {
this.setState({
actors: contacts.slice(0, 6)
})

Though it's not very clear from your given codebase what is the issue but one possible error you could make is that you are not binding addRandomContact inside constructor of that class component. Try to paste the following code in your constructor and check if it solves
this.addRandomContact = this.addRandomContact.bind(this);

Related

Error in Pure Componenet State in React-Redux

I am facing a bizarre error. PFB:
I am actually using a PureComponent Class and on componentWillReceiveProps method, I am updating the current state with the nextPropValues. Data is all coming perfectly but I am getting undefined error when I assign the values thru setState method. Hence I tried Console.log it, the data objects are received properly but when I try to access the attributes inside the object I am getting Undefined. Can you make me understand where I had made a mistake?
Thanks!
Console:
Debugging Mode:
As you can see below when I access the attributes inside the book object, I am getting undefined.
Console:
Debugging Mode:
Thank you so much for all of your replies.
As in the below code: I have fixed it by adding a if(book) {this.setState(...)}...
But not sure on which hook it is getting undefined.
Explanation:
This is because, Initially as the component renders this book object will be empty, as I am accessing the attributes inside book object, it throws an undefined error. So I gave an If condition, hence it skips the setState method where I am accessing the book object's attribute. Hope I was clear.
Thanks, Guys
componentWillReceiveProps(nextProps) {
// debugger;
let book = nextProps.books.book;
// console.log(book);
if (book) {
// console.log(book._id);
this.setState({
formdata: {
_id: book._id,
name: book.name,
author: book.author,
review: book.review,
pages: book.pages,
rating: book.rating,
price: book.price,
},
});
}
}

how to fix this error "Cannot set property 't' of undefined" in react?

I am new on react
I tried to execute this function in react
export default class App extends Component{
render(){
function SSS(t)
{
this.t=t;
return this;
}
console.log(SSS(1).t);
}return(
<h1>H</h1>
)}
}
but it still gives me that error
TypeError: Cannot set property 't' of undefined
I read about "this" in MDN
they mentioned the reason of this error is how to call the function
it works perfectly on js pure.
could you help me with that,please ?
thnx!
SSS function call should assign t variable onto its execution context, e.g., if you call it in within window object, the variable can be accessed from there,
window.t // 1. Provided you are in 'use strict' mode., you will get
TypeError: Cannot set property 't' of undefined
If you want to bind custom context to SSS, you should either use call/apply/bind, examples:
SSS.call({}, 1)
SSS.apply({}, [1])
SSS.bind({})(1);
or constructor call:
new SSS(1);
Welcome to StackOverflow.
You're using "this" in a function-in-function, "this" is not defined there.
What you want is put SSS(t) outside of render, as a class method.
Like this:
export default class App extends Component{
SSS(t)
{
this.t=t;
return this;
}
render(){
console.log(this.SSS(1).t);
return(
<h1>H</h1>
);
}
}
Also, not that doing this.t = t is dangerous in React. You should probably use this.state.t and this.setState() instead. Check this for more info :
Why can't I directly modify a component's state, really?
https://reactjs.org/docs/state-and-lifecycle.html

Accessing this object in componentdidmount

I'm having a problem with accessing/triggering functions from componentDidMount in React. All this references seem to be undefined even if I try binding the method in the constructor like this:
this.componentDidMount = this.componentDidMount.bind(this);
Here is a part of the code; I'm accessing events on leaflet maps and printing map boundaries to the console - which works fine (and that's the reason I need to use componentDidMount)
componentDidMount(){
let mapInst = this.refs.map.leafletElement;
mapInst.on('moveend', function () {
console.log(mapInst.getBounds())
});
mapInst.on('dragend', function () {
console.log(mapInst.getBounds())
});
}
Now I would like to pass those boundaries to state parameters or launch a function on callback to a parent element.
updateParent = (newBounds) => {
this.props.parentCallback({'bounds': newBounds});
}
However whatever construction I try, any function in higher scope is always undefined. It seems I cannot access neither updateParent(mapInst.getBounds()) nor this.updateParent(mapInst.getBounds()) from within componentDidMount.
Does anybody have any idea what the optimal construction in such cases is?
Full code for reference: https://pastebin.com/gQqazSCs
I think you want to use leaflet's whenReady callback.
handleMapReady = ({ target }) => {
this.setState({ leafletMapElt: target });
};
...
<Map whenReady={this.handleMapReady}>...</Map>
I don't think the map is guaranteed to be in a "ready" state in componentDidMount
Make callback function of mapInst.on to arrow function and then try to access updateParent like this mapInst.on('moveend', ()=> { this.updateParent(mapInst.getBounds()) });
Arrow function will take its surrounding this

why would this.state not be available in this scenario?

I have a component with the following functions:
constructor(MyProps: Readonly<MyProps>){
super(MyProps);
this.state = {suppliers: [], supplierId:0, supplierName:''};
this.addSupplier.bind(this);
}
addSupplier(){
const {supplierId} = this.state;
alert('supplierId = ' + supplierId);
}
<Button onClick={this.addSupplier}>Add</Button>
State is initialized as expected b/c this.state.supplierId is bound and displayed as expected in an html input in the component on load. The onChange handler within the html input also calls setState to update state.supplierId as expected. However, when the addSupplier() button gets triggered, the following error occurs:
TypeError: Cannot read property 'supplierId' of undefined
So for some reason, state is not available in this context. Any idea why this is?
Please use the arrow function to create the method
addSupplier = () => {}
or use the below syntax in the constructor
this.addSupplier = this.addSupplier.bind(this);
To expand on what Nikhil Goyal posted, the reason you're getting an error is because the context of this where the function is being invoked. Non-arrow functions implicitly bind their context when invoked rather then when they're declared. So, when you press the onClick on the Button component, it's searching for this.state.supplierId on the Button context.

Can't access to response object with props

Im building an app with reactjs & redux and facing the following problem.
So basically I have a function like this :
onAdmissionFormSubmit(e){
e.preventDefault();
const { user } = this.props
console.log(user);
// If I do this const id = user.member.externalMemberId ....
// doesnt throw an error but if I log my const id it just says its undefined
}
It actually logs my object but if want to access the data inside of the object like user.member.externalMemberId it actually doesnt return an error but it will just says undefined.
What is it that im doing wrong?
console log of user: http://prntscr.com/fcxmou
According to your comments it seems that user is undefined, that leads me to believe that either you don't have a user object in this.props or you don't have a props object in this.
If it is the second choice, that can happen if you don't bind the handler method in to the class. In this situation, this refers to the element that triggered the handler and not to the class like you would expect.
You should do the binding in the constructor of the class:
constructor(props) {
super(props);
this.onAdmissionFormSubmit = this.onAdmissionFormSubmit.bind(this);
}

Resources