Reputation: 67
You guys have seen the error,Warning: Can't call setState on a component that is not yet mounted. This is a no-op, but it might indicate a bug in your application. Instead, assign to ``this.state`` directly or define a
state = {}; class property with the desired state in the ImageTableItemComponent component.
I've seen similiar questions asked, but no answers that help me. Here is my constructor:
export default class ImageTableItemComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
data : [], // ****** This one's the problem *****
collapsible : false,
}
this.loadImagesWithTags();
}
And here is the loadImagesWithTags()
function, where I use setState
:
loadImagesWithTags() {
const imagesAndTags = new ImagesAndTags();
imagesAndTags.getImagesWithTags()
.then(imagesAndTags => {
const data = this.convertDataToObject(imagesAndTags)
this.setState({data: data,}) // ****** Here I use setState *****
})
.catch(reason => {
console.error('Error loading tags:', reason)
});
}
I have used this same method before, without recieving any kind of error. Could there be a bug or an outdated dependency or something, anything that I'm not seeing here be triggering this error? I've removed anything that has anything to do with collapsible: false,
in my code, so I know the error is in regards to data. Any help is appreciated.
Upvotes: 1
Views: 2790
Reputation: 3299
You shouldn't call methods that assign state after an async operation in the constructor. Instead, run the method in componentDidMount()
componentDidMount() {
this.loadImagesWithTags();
}
I think the error is misleading you. It's not that the component isn't mounting, but rather that you are executing the state update at the wrong moment within the React component lifecycle.
Upvotes: 2