I am setting the state in a method call from a constructor but the state property is still null. Some modification on the code gives be this error in the console,
index.js:1375 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 ResultContainer component.
In my component constructor i am calling a method. That method in turn calls another method and is trying populate an state property with an array. I get two different variants of error/warning. In my code if uncomment the lines inside render method i get searchedAddress is null error. if i leave the lines as commented then in the console i get the above error.
On my render() method i can check for null and that certainly does not throw and error but the the result items are not getting loaded no matter what i do. this question, State not changing after calling this.setState seems somewhat relevant but i am not sure i could i re-render the item asynchronously.
import React from 'react';
import ResultItem from './ResultItem'
import AddressService from '../Api/AddressService'
class ResultContainer extends React.Component{
constructor(props){
super(props);
this.state = {
searchedAddresses : null
}
this.intiateSearch();
}
intiateSearch =() => {
if(this.props.searchedTerm != null){
var addressService = new AddressService();
//this is just getting an items from json for now. i checked and result does contain items
var result = addressService.searchAddress(this.props.searchedAddresses);
//the below line does not seem to work
this.setState({
searchedAddresses : result
});
}
}
render(){
return(
<div className="mt-3">
<h4>Seaching for postcode - <em className="text-primary">{this.props.searchedTerm}</em></h4>
<div className="container mt-1">
{
//below gives an error stating searchedAddresses is null
// this.state.searchedAddresses.map((address, index)=>{
// return(<ResultItem address={address}/>);
// })
}
</div>
</div>
);
}
}
export default ResultContainer;
You shouldn't call component functions inside of the constructor method, the component is not yet mounted at this point and therefore your component functions aren't available to be used here yet. In order to update your state. You used to be able to use the componentWillMount lifecycle method but that is now considered legacy. You should be calling any component initializing functions inside of the componentDidMount lifecycle method.
Change your code like so :
(Notice the check for state initially being null in the render function)
import React from 'react';
import ResultItem from './ResultItem'
import AddressService from '../Api/AddressService'
class ResultContainer extends React.Component{
constructor(props){
super(props);
this.state = {
searchedAddresses : null
}
}
componentDidMount() {
this.intiateSearch();
}
intiateSearch =() => {
if(this.props.searchedTerm != null){
var addressService = new AddressService();
//this is just getting an items from json for now. i checked and result does contain items
var result = addressService.searchAddress(this.props.searchedAddresses);
this.setState({
searchedAddresses : result
});
}
}
render(){
return(
<div className="mt-3">
<h4>Seaching for postcode - <em className="text-primary">{this.props.searchedTerm}</em></h4>
<div className="container mt-1">
{
this.state.searchedAddresses !== null &&
this.state.searchedAddresses.map((address, index)=>{
return(<ResultItem address={address}/>);
})
}
</div>
</div>
);
}
}
export default ResultContainer;
I see you're calling this.intiateSearch(); in constructor which will call setState on a not yet mounted component.
So why don't you call this.intiateSearch(); inside componentDidMount() lifecyle after the component is mounted?
componentDidMount() {
this.intiateSearch();
}
Related
tell me, please, how to solve the following problem correctly?
I have a certain component, there is a control above, when I click on it, setState is triggered. I need to call the function this.setScrollLeft () in which I set to the selected node (ref) in this case the cleavage position.
Here is my implementation, but I am sure that there is a better solution:
import React from 'react';
import { ScoreCell, getScoreTheme } from 'components/scores';
class LeaderboardPlayerResult extends React.Component {
constructor(props) {
super(props);
this.containerWidth = 198;
this.data = this.props.data;
this.playerResultRef = React.createRef();
}
componentDidMount() {
this.element = this.playerResultRef.current;
this.element.scrollLeft = this.containerWidth;
}
setScrollLeft = () => {
if (this.element) {
this.element.scrollLeft = this.containerWidth;
}
};
playerResult = () => {
if (this.data.playOffHoles) {
return (
this.data.playOffHoles.map((item, index) => {
return (
<div
className="leaderboard__player-result-row-wrapper"
key={index}
>
<div className="leaderboard__player-result-row">
<div className="leaderboard__player-result-cell">{item.holeId}</div>
</div>
<div className="leaderboard__player-result-row">
<div className="leaderboard__player-result-cell">{item.holePar}</div>
</div>
<div className="leaderboard__player-result-row">
<div className="leaderboard__player-result-cell leaderboard__player-result-cell--score">
<ScoreCell
childCss='tee-times-card__score'
theme={getScoreTheme(item.playOffParScore)}
>{item.playOffParScore}</ScoreCell>
</div>
</div>
</div>
);
})
);
}
};
render() {
console.log('LeaderboardPlayerResult render');
this.setScrollLeft();
return (
<div
className="leaderboard__player-result"
ref={this.playerResultRef}
>
{this.playerResult()}
</div>
);
}
}
The best place to put this.setScrollLeft() is inside the componentDidUpdate method.
You are already calling this method (this.setScrollLeft()) inside componentDidMount, what is right. Now, you could put another call into componentDidUpdate and it will work pretty much as it is working by now because componentDidUpdate is called before render.
The final outcome will be the same, however, you are separating the concerns: render only render the components and the other methods deal with your business logic.
If you are not sure about componentDidMount and componentDidUpdate, see these excerpts from the official React.js documentation:
componentDidMount()
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.
componentDidUpdate()
componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.
I couldn't find a related situation to mines, however my problem I am having a common error of TypeError: Cannot read property 'props' of undefined.
Weird part is, this error is occurring only for the method I defined above render().
Inside of render() I am able to have access without errors though. React dev tools shows I even have access to props.
Code below:
import { Route } from 'react-router-dom'
import AuthService from '../../utils/authentication/AuthService'
import withAuth from '../../utils/authentication/withAuth'
const Auth = new AuthService()
class HomePage extends Component {
handleLogout() {
Auth.logout()
this.props.history.replace('/login')
}
render() {
console.log(this.props.history)
return (
<div>
<div className="App-header">
<h2>Welcome {this.props.user.userId}</h2>
</div>
<p className="App-intro">
<button type="button" className="form-submit" onClick={this.handleLogout}>Logout</button>
</p>
</div>
)
}
}
export default withAuth(HomePage)
Edit: Apologies. I don't want to cause a confusion either, so I will add that I am also using #babel/plugin-proposal-class-propertiesto avoid this binding.
It's because your method handleLogout has it's own context. In order to pass the this value of the class to your method have to do one of two things:
1) Bind it inside the constructor of the class:
constructor(props) {
super(props)
this.handleLogout = this.handleLogout.bind(this)
}
2) You declare your handleLogout method as an arrow function
handleLogout = () => {
console.log(this.props)
}
this isn't bound in non es6 I believe. So you could either bind it with a constructor, or you may be able to get away with an es6 type function
handleLogout = () => {
Auth.logout()
this.props.history.replace('/login')
}
I can't try this, but you could also do a
constructor(props) {
super(props);
// Don't call this.setState() here!
this.handleLogOut= this.handleLogOut.bind(this);
}
You need to use .bind on your click handler.
<button type="button" className="form-submit" onClick={this.handleLogout.bind(this)}>Logout</button>
I'm trying to make a todo list app with React and Firebase.
It's a single page app (except for login).
In my Page's component, I call to a List's component.
In my List's component, I get my firebase data that I put in a state.
In React Dev Tool, in my List's component, I can see a state like this :
list{items{...},listName:"exemple"}
So, in my return, I'm trying to show the listName's value like that: {this.state.list.listName}
But I have the following error: : Cannot read property 'listName' of null
This is my List's component :
class ListPage extends Component {
constructor(props) {
super(props);
this.state = {
list: null,
};
}
componentDidMount() {
this.listRef = db.ref(`users/${this.props.user.uid}/lists
${this.props.cle}`);
this.listRef.on('value', data=>{
this.setState({
list: data.val()
})
})
}
render() {
return (
<div>
<h1>List : {this.state.list.listName}</h1>
</div>
);
}
}
Where I am wrong ?
Thanks
The reason is because when your component first mounts, the state list is null. Only when the asynchronous firebase response comes back is it loaded with data and becomes non-null. The solution is to check if it's null, so in your render() function change this part:
<h1>List : {this.state.list.listName}</h1>
to this:
{ this.state.list && <h1>List : {this.state.list.listName}</h1> }
In general it's good to check if objects are defined before accessing their properties. Especially ones you've explicitly defined to be null at some point.
I have a little piece of code that renders data from the database according to the path name. My only problem is that when I try to retrieve that data, using this.state.note._id it returns an error that says it cannot find _id of undefined. How would I access my object that is put into a state? It only gives the error when I try to access the items inside the object such as _id
import React from "react";
import { Tracker } from "meteor/tracker";
import { Notes } from "../methods/methods";
export default class fullSize extends React.Component{
constructor(props){
super(props);
this.state = {
note: [],
document: (<div></div>)
};
}
componentWillMount() {
this.tracker = Tracker.autorun(() => {
Meteor.subscribe('notes');
let note = Notes.find({_id: this.props.match.params.noteId}).fetch()
this.setState({ note: note[0] });
});
}
renderDocument(){
console.log(this.state.note);
return <p>Hi</p>
}
componentWillUnmount() {
this.tracker.stop();
}
render(){
return <div>{this.renderDocument()}</div>
}
}
I know that the reason it is returning undefined is because (correct me if I am wrong) the page is rendering the function before the the tracker could refresh the data. How would I get like some sort of callback when the tracker receives some data it will call the renderDocument function?
You're initializing your note state as an array but then you're setting it to a scalar later. You're also not checking to see if the subscription is ready which means that you end up trying to get the state when it is still empty. The tracker will run anytime a reactive data source inside it changes. This means you don't need a callback, you just add any code you want to run inside the tracker itself.
You also don't need a state variable for the document contents itself, your render function can just return a <div /> until the subscription becomes ready.
Note also that .findOne() is equivalent to .find().fetch()[0] - it returns a single document.
When you're searching on _id you can shorthand your query to .findOne(id) instead of .findOne({_id: id})
import React from "react";
import { Tracker } from "meteor/tracker";
import { Notes } from "../methods/methods";
export default class fullSize extends React.Component{
constructor(props){
super(props);
this.state = {
note: null
};
}
componentWillMount() {
const sub = Meteor.subscribe('notes');
this.tracker = Tracker.autorun(() => {
if (sub.ready) this.setState({ note: Notes.findOne(this.props.match.params.noteId) });
});
}
renderDocument(){
return this.state.note ? <p>Hi</p> : <div />;
}
componentWillUnmount() {
this.tracker.stop();
}
render(){
return <div>{this.renderDocument()}</div>
}
}
I have a component that receives images as props, performs some calculation on them, and as a result I need to update its class. But if I use setState after the calculation, I get the warning that I shouldn't update state yet... How should I restructure this?
class MyImageGallery extends React.Component {
//[Other React Code]
getImages() {
//Some calculation based on this.props.images, which is coming from the parent component
//NEED TO UPDATE STATE HERE?
}
//componentWillUpdate()? componentDidUpdate()? componentWillMount()? componentDidMount()? {
//I CAN ADD CLASS HERE USING REF, BUT THEN THE COMPONENT'S
// FIRST RENDERED WITHOUT THE CLASS AND IT'S ONLY ADDED LATER
}
render() {
return (
<div ref="galleryWrapper" className={GET FROM STATE????}
<ImageGallery
items={this.getImages()}
/>
</div>
);
} }
You should put your logic into componentWillReceiveProps (https://facebook.github.io/react/docs/component-specs.html#updating-componentwillreceiveprops) so as to do a prop transition before render occurs.
In the end what we did was run the logic in the constructor and then put the class into the initial state:
class MyImageGallery extends React.Component {
constructor(props) {
super(props);
this.getImages = this.getImages.bind(this);
this.images = this.getImages();
this.state = {smallImgsWidthClass: this.smallImgsWidthClass};
}
getImages() {
//Some calculation based on this.props.images, which is coming from the parent component
this.smallImgsWidthClass = '[calculation result]';
return this.props.images;
}
render() {
return (
<div className={this.state.smallImgsWidthClass }
<ImageGallery
items={this.images}
/>
</div>
);
}
}