Search code examples
reactjsreact-nativereact-state-management

React - Invariant Violation: Maximum update depth exceeded


I have function for set my state from another class, but i got this following 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.

And here's my code looks like

  constructor(props) {
    super(props)
    this.state = { loading: true, showAction: false }
    setTimeout(() => {
      StatusBar.setBackgroundColor(primary)
    }, 100)
  }

  async componentWillMount() {
    await Font.loadAsync({
      Roboto: require("native-base/Fonts/Roboto.ttf"),
      Roboto_medium: require("native-base/Fonts/Roboto_medium.ttf"),
      Ionicons: require("@expo/vector-icons/build/vendor/react-native-vector-icons/Fonts/Ionicons.ttf"),
    });
    this.setState({ loading: false });
  }

  setShowAction = (isShowAction) => {
    console.log(isShowAction)
    this.setState({
      showAction: isShowAction
    })
  }

...

<ChatListScreen onAction={(isShowAction) => this.setShowAction(isShowAction)}/>

...

const ChatListScreen = ({ onAction }) => {

    return (
        <ChatList onAction={(isShowAction) => onAction(isShowAction)}/>
    )
}

...

const ChatList = ({ onAction }) => {
    const [selectMode, setSelectMode] = useState(false)
    const chatListDummy = []
    const [selectedItem, setSelectedItem] = useState([])
    {selectMode ? onAction(true) : onAction(false)}
    return (
        <FlatList
                data= {chatListDummy}
                keyExtractor= {chat => chat.id}
                renderItem= {({item}) => {
                }}/>
    )
}

export default ChatList

Can anyone help?


Solution

  • see my solution

    const ChatListScreen = ({ onAction }) => {
    
       return (
           <ChatList onAction={(isShowAction) => onAction(isShowAction)}/>
       )
    }
    const ChatList = ({ onAction }) => {
       const [selectMode, setSelectMode] = useState(false)
       const [selectedItem, setSelectedItem] = useState([])
       //i dont know where are you using this actally you most use this in a lifesycle or a function
       // {selectMode ? onAction(true) : onAction(false)}
    function onClick(){
       selectMode ? onAction(true) : onAction(false)
    
    }
    //or a lifecycle
    useEffect(()=>{
       selectMode ? onAction(true) : onAction(false)
    
    },[])
    return (<div onClick ={onClick} >{"your content"}</div>)