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,
},
});
}
}
Related
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);
I'm having a strange issue with state in my React app. I set initial state as an empty array and in the componentDidMount() method I retrieve some data from Firebase. I put the JSON objects into a new array and call setState(), passing it the new array.
The problem is that it doesn't seem to be updating state. From what I can tell:
Render() is being called after setState
My callback on setState() is being fired
When I console.log the array that I set the state to, it looks fine
The strangest thing, when I inspect state in the Chrome React Devtools, it shows empty but for some reason I can print the array to the console using $r.state.nameOfMyObject
If I change some other piece of state directly from the dev tools, the app immediately renders and finally displays the piece of data I've been struggling with all along.
I thought maybe there was some issue with updating the array; maybe the diffing algorithm didn't go deep enough to see that the data inside the array changed. To test this, I tried to set the initial state of the object in question to null, but then set off errors throughout the app that it was trying to call various array methods on null.
I've tried walking through the app, console logging each step, but I can't find the issue.
Snippet of initial state:
state = {
fullSchedule: [],
currentSet: [],
aCoupleOfOtherObjects,
}
componentDidMount():
componentDidMount() {
const activities = [];
const projectReference = firestoreDB.collection("project").doc("revision001").collection("activities");
projectReference.get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
activities.push(doc.data());
});
});
console.log(activities);
this.setState({fullSchedule: activities});
this.setState({currentSet: activities}, () => {
console.log("State updated from DB");
});
console.log("called setstate");
}
I can't tell why the setState() method doesn't seem to be setting the state, any ideas?
Thanks!
projectReference.get() is asynchronous, and you are trying to set the state right after you call it, which won't work.
try setting the state inside then callback:
projectReference.get().then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
activities.push(doc.data());
});
this.setState({fullSchedule: activities, currentSet: activities});
});
This should give you a better idea of what's going on.
I have a query called GET_ME and another one called GET_USER_NOTIFICATIONS. Second one it's looking for user id which will come from first query. My problem is that sometimes I receive [TypeError: undefined is not an object (evaluating 'o.props.getMe.me._id')]
Here is my code for this:
export default compose(
withApollo,
graphql(GET_ME, { name: "getMe" }),
graphql(GET_USER_NOTIFICATIONS, {
name: "notification",
skip: props => !props.getMe || !props.getMe.me,
options: props => ({
variables: { r_id: props.getMe.me._id }
})
})
)(Notifications);
Any help?
Can you try doing:
variables: { r_id: props.getMe && props.getMe.me ? props.getMe.me._id : null }
// I use "null" in case the object doesn't exists.
// You can use value that your graphql needs.
(you could also use lodash for simplicity _.get(...))
The error suggests that it's executing the variables assignment although you have set the query to be skipped. But at the time of the assignment either getMe or getMe.me is "undefined".
If that doesn't help, you can use the Render props Apollo components inside of the render method. That way, you can guarantee you can't set the variable without getting access to getMe.me._id.
I'm trying to access to a json object using dot notation but it throws me an error. Here's my code: https://codepen.io/manAbl/pen/aGymRg?editors=0110
I'm destructuring like this: const { weather } = this.state;
And when I do: console.log(weather) It shows me the hole json object, just fine but when I try to do console.log(weather.name) the console throws me an error
What am I doing wrong? I must be missing something easy but I can't see it and I'm stuck
I want to be able to access the properties and set them as a value on my state, so I can them write some functions to display an icon depending on what is the current weather of the location
this.state.weather is null initially (before the setState in componentDidMount is called), so you need to check if it's not null first before accessing the properties.
Alternatively, set weather to {} instead of null initially.
You initialize your state like this :
this.state = {
weather: null,
loading: true,
};
Then you're updating the weather var in your componentDidMount
componentDidMount is fired after the render method is called
So the 1st time the render method is called, your weather var is null and filled after componentDidMount is called
You should do
this.state = {
weather: {},
loading: true,
};
or check if your var isn't null
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);
}