I'm working with react and I'm trying to set state on page render but it keeps throwing the below error.
---Error----
Maximum update depth exceeded. This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. React limits the number of nested updates to prevent infinite loops.
---Error----
Below is my code of the sidebar component. I'm using Context API for data management as shown in the code and I'm trying to set state of the role inside the showContext method with the value I'm getting through the Context API Consumer.
import React, { Component, PropTypes } from "react";
import { Menu, Icon } from "antd";
import { BrowserRouter as Router, Link, Route, Switch } from "react-router-dom";
import AdminPage from "../components/Admin/AdminPage";
import App from "../App";
import "../components/Login/LoginPage";
import { LoginContext } from "../context/LoginContext";
export default class MainMenu extends React.Component {
constructor(props) {
super(props);
this.state = {
roleValue: "admin",
status: false
};
this.showContext = this.showContext.bind(this);
}
showContext(context) {
let role = context;
if (this.state.roleValue == role) {
this.setState({
roleValue : "admin",
});
}
}
render() {
if (window.location.href == "http://localhost:8081/") {
var loginHeader =
<Menu
theme="dark"
mode="horizontal"
defaultSelectedKeys={["2"]}
selectedKeys={[location.pathname]}
>
{this.props.children}
<Menu.Item key="mastering">Mastering</Menu.Item>
</Menu>;
}
else {
if (this.state.roleValue == "general") {
var generalHeader1 =
<Menu
theme="dark"
mode="horizontal"
defaultSelectedKeys={["2"]}
selectedKeys={[location.pathname]}
>
{this.props.children}
<Menu.Item key="mastering">Mastering</Menu.Item>
<Menu.Item>
<Link to="/"> Logout</Link>
</Menu.Item>
<Menu.Item>
<Link to="/home">Home</Link>
</Menu.Item>
</Menu>;
}
else {
var generalHeader2 =
<Menu
theme="dark"
mode="horizontal"
defaultSelectedKeys={["2"]}
selectedKeys={[location.pathname]}
>
{this.props.children}
<Menu.Item key="mastering">Mastering</Menu.Item>
<Menu.Item>
<Link to="/"> Logout</Link>
</Menu.Item>
<Menu.Item>
<Link to="/admin">Admin</Link>
</Menu.Item>
<Menu.Item>
<Link to="/home">Home</Link>
</Menu.Item>
</Menu>;
}
}
return (
<div>
{loginHeader}
{generalHeader1}
{generalHeader2}
<LoginContext.Consumer>
{(context) => (
this.showContext(context.state.role)
)
}
</LoginContext.Consumer>
</div>
);
}
}