Problem with setState in React Native: "Can’t call 'setState' on a Component that is not yet Mounted."

Asked

Viewed 130 times

1

all right? I’m a beginner in React Native and in this app I’m making I can’t call 'setState' in the method I created. The name of the method I created is called includingMed() and I call it here

constructor() {
    super()
    this.state = {
      isVisible: false,
      newMed: [],
      medName: "",
      medInitHour: null,
      medTimes: null
    }
  }

  addMed = () => { 
    if(!this.state.medName.trim() || !this.state.medTimes){
      Alert.alert('Dados inválidos!','Verifique se todos os campos estão preenchidos.');
      return
    }

    try {
      this.setState({
        newMed: this.state.newMed.push({
          medName: this.state.medName,
          medInitHour: this.state.medInitHour,
          medTimes: this.state.medTimes
        }),
        medInitHour: null,
        medTimes: null,
        medName: ""
      });
      var include = new MedList();
      include.includingMed(this.state.newMed);

      this.setState({newMed: []});

      ToastAndroid.show('Medicamento Adicionado!', ToastAndroid.SHORT);
    }catch (ex){
      ToastAndroid.show('Falha ao adicionar. Erro: '+ex, ToastAndroid.SHORT);
    }
  }

And down here is all his programming which is where setState() fails to run and returns me that message:

includingMed = newMed => {
    const meds = [...this.state.meds];
    meds.push({
      id: Math.random(),
      medName: newMed.medName,
      medInitHour: newMed.medInit,
      medTimes: newMed.medTimes
    });

    this.setState({ meds });
  }

Please, I would really appreciate it if someone could help me in this app, it’s my first time kkk Thank you, hug!!

  • 1

    Hello Pablo, put the complete code of your file, to facilitate the analysis of the error!

2 answers

0

Try using this: this.setState(this.state);

-1

import React from 'react';
import { ExpoConfigView } from '@expo/samples';
//import Meds from '../components/Meds'
import {
  FlatList,
  View,
  Text,
  StyleSheet
} from 'react-native';
import Meds from '../components/Meds';
import 'regenerator-runtime/runtime';


export default class MedList extends React.Component {
  static navigationOptions = {
    title: 'Remédios',
  };

  state = {
    meds: [
      { id: Math.random(), medName: 'Diclofenaco', medInitHour: 0, medTimes: 3 },
      { id: Math.random(), medName: 'Aspirina', medInitHour: 0, medTimes: 4 },
      { id: Math.random(), medName: 'Cimegripe', medInitHour: 0, medTimes: 2 },
      { id: Math.random(), medName: 'Diclofenaco', medInitHour: 0, medTimes: 3 },
      { id: Math.random(), medName: 'Aspirina', medInitHour: 0, medTimes: 4 },
      { id: Math.random(), medName: 'Cimegripe', medInitHour: 0, medTimes: 2 },
      { id: Math.random(), medName: 'Diclofenaco', medInitHour: 0, medTimes: 3 },
      { id: Math.random(), medName: 'Aspirina', medInitHour: 0, medTimes: 4 },
      { id: Math.random(), medName: 'Cimegripe', medInitHour: 0, medTimes: 2 },
      { id: Math.random(), medName: 'Diclofenaco', medInitHour: 0, medTimes: 3 },
      { id: Math.random(), medName: 'Aspirina', medInitHour: 0, medTimes: 4 },
      { id: Math.random(), medName: 'Cimegripe', medInitHour: 0, medTimes: 2 }
    ]
  }

  includingMed = newMed => {
    const meds = [...this.state.meds];
    meds.push({
      id: Math.random(),
      medName: newMed.medName,
      medInitHour: newMed.medInit,
      medTimes: newMed.medTimes
    });

    this.setState({ meds });
  }

  render() {
    /* Go ahead and delete ExpoConfigView and replace it with your
     * content, we just wanted to give you a quick view of your config */
    //return <ExpoConfigView />;

    return (
      <View style={styles.container}>
        <View>
          <Text>Ainda vou colocar alguma coisa aqui</Text>
        </View>
        <View style={styles.list}>
          <FlatList data={this.state.meds}
            keyExtractor={item => `${item.id}`}
            renderItem={({ item }) => <Meds {...item} />}>
          </FlatList>
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  item: {
    backgroundColor: '#aaa',
    padding: 30,
    margin: 10,
    width: '75%',
    color: '#fff'
  },
  container: {
    backgroundColor: 'rgba(113, 165, 237, 0.4)'
  },
  list: {
    marginBottom: 40
  }
});

It’s in this file where I’m having problems with setState()

Browser other questions tagged

You are not signed in. Login or sign up in order to post.