Home > Enterprise >  React Native : Rendered more hooks than during the previous render
React Native : Rendered more hooks than during the previous render

Time:01-10

I am getting this error after implementing the gethomeid useState and cant understand I tried different things but nothing worked

import React, {useEffect, useState} from 'react';
import {
  StyleSheet,
  View,
  Image,
  Text,
  TouchableOpacity,
  Button,
} from 'react-native';
import {windowWidth, windowHeight} from '../utils/Dimentions';
//components
import EmptyContainer from '../components/EmptyContainer';
import Header from '../components/Header';
import TopTabs from '../components/Tabs';

//redux
import {getHomeData} from '../action/homedata';
import {connect} from 'react-redux';
import propTypes from 'prop-types';

// to render empty container

const Home = ({getHomeData, homeState, userDetails}) => {
  const [gethomeid, setGethomeid] = useState(null);
  if (userDetails) {
    useEffect(() => {
      getHomeData('123456');
    }, []);
  }
  if (homeState.data != null && userDetails && gethomeid != null) {
    console.log(homeState.data);
    return (
      <View style={{flex: 1}}>
        <Header username={userDetails.name.split(' ')[0]} />
        <TopTabs roomdata={homeState.data.roomMapper} />
      </View>
    );
  } else {
    return (
      <View>
        <EmptyContainer />
      </View>
    );
  }
};

const mapStateToProps = state => ({
  homeState: state.data,
  userDetails: state.auth.user,
});

const mapDispatchToProps = {
  getHomeData,
};

Home.propTypes = {
  getHomeData: propTypes.func.isRequired,
  homeState: propTypes.object.isRequired,
  userDetails: propTypes.object,
};

export default connect(mapStateToProps, mapDispatchToProps)(Home);

I am trying to load 2 buttons that will pass the data on clicked to the gethomeid but this error i am not able to solve

THE SNAPSHOT OF THE ERROR:- enter image description here

enter image description here

CodePudding user response:

You are conditionally calling the useEffect hook. This breaks the rules of hooks. You can likely move the conditional into the hook callback.

useEffect(() => {
  if (userDetails) {
    getHomeData('123456');
  }
}, []);

You should probably also add any missing dependencies the linter may complain about, like userDetails and getHomeData.

useEffect(() => {
  if (userDetails) {
    getHomeData('123456');
  }
}, [getHomeData, userDetails]);
  •  Tags:  
  • Related