Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

error: attempted to update component that has already been unmounted (or failed to mount)

I'm new to React, I'm having trouble rendering my app due to this error. It's seems the data that I'm trying to render as elements won't render due to trying to set state when unmounted?

I'm not sure how I'm getting this error, as I'm setting the state of Data in componentDidMount.

How can I fix this issue?

error: attempted to update component that has already been unmounted (or failed to mount)

class Profile extends React.PureComponent {
  static propTypes = {
    navigation: PropTypes.object,
    handleLogout: PropTypes.func,
    user: PropTypes.object,
  };

  static navigationOptions = {
    headerVisible: true,
    title: 'Profile',
  };

constructor(props) {
    super(props);

    this.state = {
    data: [],
    loading: true

    };
  }

componentDidMount() {

  fetch("http://10.0.2.2:8080/combined", { method: 'get' })
    .then(response => response.json())
    .then(data => {
      this.setState({data: data,});

    })
   .catch(function(err) {
     // 
   })
}

 render() {

    const { user } = this.props;
    let email;

    if (user) {
      email = user.rows[0].ACCTNO;
    }
    return (
      <ContentWrapper>
        <View style={styles.container}>
          <Image style={styles.header} source={images.profileHeader} />
          <View style={styles.body}>
            <Avatar email={email} style={styles.avatar} />
             {
   this.state.data.map(function(rows, i){
         this.setState({mounted:  true});

    return(
      <View key={i}>
        <Text>{rows.FIRSTNAME}</Text>
      </View>
    );
  })
}            <Text style={styles.email}>{_.capitalize(email)}</Text>

            <Button
              title="Log out"
              icon={{ name: 'logout-variant', type: 'material-community' }}
              onPress={this.logout}
              style={styles.logoutButton}
            />
          </View>
        </View>
      </ContentWrapper>
    );
  }
}

export default Profile;
like image 905
sortinousn Avatar asked May 17 '17 17:05

sortinousn


2 Answers

There is another way this error can occur...thinking that props are individual arguments (props is actually a single argument)

import React from 'react';

const Posts = posts => {       // WRONG

const Posts = ({posts}) => {   // RIGHT
  const renderPosts = () => {
    return posts.map(post => <div>{post.title}</div>);
  };

  return <div>{renderPosts()}</div>;
};
like image 64
lukeaus Avatar answered Sep 19 '22 16:09

lukeaus


My problem is I forget

import React from 'react'

in my .jsx file, since I thought importing React is not needed in functional component.

like image 42
jasonxia23 Avatar answered Sep 19 '22 16:09

jasonxia23