Search code examples
reactjsreact-state-management

Where to set state when I need that state in render?


I am getting this error below:

react_devtools_backend.js:2430 Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

From the error, I know I am getting it because I am setting state in the render.

But I am not sure where to set the state because I need that state element, developerTitle further down inside the render method.

Where can I put it if not in render?

Thanks!

Here is my code:

export default class Game extends React.PureComponent {
    constructor(props) {
        super(props);

        this.state = {
            developerTitle: ''
        }
    }

    render() {
        const { indieDeveloperId } = this.props;
        this.setState({ developerTitle: this.getDeveloperTitle(game.indieDeveloperId) });
        
            <div>

                <h3>{this.state.developerTitle}</h3>
                ...
                ...
            </div>
    }
    
    //by-indie-developer/{indieDeveloperId
    async getDeveloperTitle(indieDeveloperId) {
        const r = await axios.get(`/api/developer/by-indie-developer/${indieDeveloperId}`);
        const developerTitle = r.data;
        this.setState({
            ...this.state, ...{
                developerTitle: developerTitle
            }
        });
    }
}

Solution

  • You can't set a state in render(). But you can set a state when the component is loaded using the componentDidMount() function. Add a function with that name like this to your component:

    componentDidMount() {
            this.setState({ developerTitle: this.getDeveloperTitle(game.indieDeveloperId) });
    }
    

    You dont have to call the function. The state will automatically be set.