skip to Main Content

I can’t be able to call a function inside component "onPress" event in a same class, it’s showing me an error like " undefined is not a function" how to solve this

here is my code overview

class UserList extends Component {

  constructor(props) {
    super(props);
    this.state = {
      user_data:[],
    };
  }

  componentDidMount() {
  }

    logOut=(ext_id)=>
      {
        console.log(ext_id);
      }


    UserItem (props,{MainScreen}){

      const navigation = useNavigation();
       const [name, setName] = useState();
       const [image_name, setImg] = useState();
    
      fetch('https://exmaple.com/info.php', {
        method: 'POST',
        mode: 'no-cors',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          'user_id': props.one,
          'key':props.three,
          'api_key':`XXXXXXXX`
        })
      }).then((response) => response.json())
      .then((json) => {
          console.log(json);
          setName(json.business_name);
          setImg(json.logo);
  
      }).catch((err) => { console.log(err); });
     
      
      return(
        <TouchableRipple
          onPress={() => {navigation.navigate('MainScreen',{one:props.one,two:props.two,three:props.three})}}
          rippleColor="rgba(0, 0, 0, .1)"
          centered={true}
          borderless={true}
          style={styles.ripple}
        >
        <Card style={{marginHorizontal:20, marginVertical:10, padding:8, flexDirection:'row'}}>
          <View style={{flexDirection:'row'}}>
              <Image
              style={{height:80,width:80,borderRadius:8}}
              source={{
                uri:`https://tridevmart.com/web_app/shop_logo/${image_name}`
              }} />
              <View style={{flex:1}}>
                  <Text numberOfLines = {1} style={{fontSize:24,margin:10}}>{name}</Text> 
                  <View style={{flexDirection:'row',justifyContent:'space-between'}}>
                    <Text numberOfLines={5} style={{fontSize:16,marginHorizontal:10,flex:1,color:`#ccc`}}>Income : 2654</Text>
                    <Button icon="logout" mode="contained" mode="text" onPress={this.logOut(props.ext)}>Logout</Button>
                  </View>
                  
              </View>
              
          </View>
         </Card>
        </TouchableRipple>
      );
      
    }


    list = () => {
        return this.state.user_data.map((element) => {
          return (
              <this.UserItem key={element.ext_id} ext={element.ext_id} one={element.one} two={element.two} three={element.three}/>
          );
        });
      };

     
  render(){
    return(
        <SafeAreaView style={{ flex: 1 }}>
            <View style={styles.mainBox}>        
              {this.list()}

              <Button mode="contained" style={styles.inputButton} onPress={() => this.props.navigation.navigate('LoginScreen')}>+ Add More Account</Button>
            </View>
        </SafeAreaView>
      );
  }
}

In here let’s see "UserItem" component. and inside this see "Logout" Button. in onPress event of logout button show me the error of "undefined is not a function"

Please try to solve my error

enter image description here

2

Answers


  1. You’re supposed to pass a function to the event handlers in react, not call the function.

    Instead of

    onPress={this.logOut(props.ext)
    

    you should be doing

    onPress={() => this.logOut(props.ext)
    

    If you don’t have anything to pass into the function you can simply do onPress={this.logOut}. Keep in mind that the event object will be passed to this.logOut as the first argument.

    Edit:
    Move the UserItem outside the other component:

    function UserItem (props,{MainScreen}){
         ...
         return(
            ...
                        <Button icon="logout" mode="contained" mode="text" onPress={() => props.logOut(props.ext)}>Logout</Button>
                      </View>
            ...
          );
          
        }
    
    class UserList extends Component {
    ...
    list = () => {
            return this.state.user_data.map((element) => {
              return (
                  <UserItem key={element.ext_id} ext={element.ext_id} one={element.one} two={element.two} three={element.three} logOut={this.logOut}/>
              );
            });
          };
    ...
    }
    
    Login or Signup to reply.
  2. I think the error is related to "this" relationship with arrow functions inside a class component in React.

    Try replacing the arrow function to a normal function

    logOut(){console.log("clicked")}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search