I'm trying to convert a Class-based component to a Functional component. I get the above-mentioned error if I use the same code that was under componentDidMount in useEffect hook.
// Class based component
class Container extends Component {
state = {
elements: [],
counter: 1,
bgColor: "#ffffff",
botTextColor: "#000000",
botBGColor: "#aaaaaa",
userTextColor: "#000000",
userBgColor: "#aaaaaa",
};
componentDidMount = async () => {
this.setState({
bgColor: this.props.chat.currentChat.bgColor,
botTextColor: this.props.chat.currentChat.botTextColor,
botBGColor: this.props.chat.currentChat.botBGColor,
userTextColor: this.props.chat.currentChat.userTextColor,
userBgColor: this.props.chat.currentChat.userBgColor,
});
this.setState({
elements:
this.props.chat.currentChat.elements &&
this.props.chat.currentChat.elements.length > 0
? elements
: [
{
id: "0",
data: {
label: (
<WelcomeNode
id={"0"}
images={this.props.chat.media.map((e) => e.file)}
updateChoices={(choices) =>
this.updateChoices("0", choices)
}
updateMessage={(message) =>
this.updateMessage("0", message)
}
updateImage={(e) => this.updateImage(e, "0")}
addEdge={this.addEdgeCustom}
deleteEdgeChoice={(index) =>
this.deleteEdgeChoice("0", index)
}
isChoiceConnected={(index) =>
this.isChoiceConnected("0", index)
}
></WelcomeNode>
),
message: "",
choices: [],
type: "welcome",
id: "0",
},
className: "node-elements",
position: { x: 100, y: 100 },
},
],
counter: elements.length > 0 ? elements.length : 1,
});
}
}
The Following is the functional component where the error occurs
// Functional component
const initialState = {.....}
const Container = () => {
const [state, setState] = useState(initialState);
const { auth, chat } = useSelector((state) => ({ ...state }));
const dispatch = useDispatch();
const history = useHistory();
useEffect(() => {
setState({
...state,
bgColor: chat.currentChat.bgColor,
botTextColor: chat.currentChat.botTextColor,
botBGColor: chat.currentChat.botBGColor,
userTextColor: chat.currentChat.userTextColor,
userBgColor: chat.currentChat.userBgColor,
});
setState({
...state,
elements:
chat.currentChat.elements && chat.currentChat.elements.length > 0
? elements
: [
{
id: "0",
data: {
label: (
<WelcomeNode
id={"0"}
images={chat.media.map((e) => e.file)}
updateChoices={(choices) => updateChoices("0", choices)}
updateMessage={(message) => updateMessage("0", message)}
updateImage={(e) => updateImage(e, "0")}
addEdge={(e) => addEdgeCustom(e)}
deleteEdgeChoice={(index) =>
deleteEdgeChoice("0", index)
}
isChoiceConnected={(index) =>
isChoiceConnected("0", index)
}
></WelcomeNode>
),
message: "",
choices: [],
type: "welcome",
id: "0",
},
className: "node-elements",
position: { x: 100, y: 100 },
},
],
counter: elements.length > 0 ? elements.length : 1,
});
}, []);
}
The following error is thrown and the browser crashes Uncaught (in promise) Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.