How to check a State to know if it is undefinied in React Native?

Asked

Viewed 363 times

-1

I’m using the React-Native-community/React-Nactive-datetimepicker as datepicker in an app, I did a treatment for when they press cancel at the time of the datepicker selection, the date value was not Undefined, but is giving this Warning every time I press cancel, I don’t know if I did the setState treatment properly. The state date is to come by default as the current date, when triggered and selected the datepicker, must change the current date to selected, or continue with the same value.

Error

 WARN  Possible Unhandled Promise Rejection (id: 0):
Invariant Violation: setState(...): takes an object of state variables to update or a function which returns an object of state variables.
http://10.0.3.2:8081/index.bundle?platform=android&dev=true&minify=false:4607:37
setState@http://10.0.3.2:8081/index.bundle?platform=android&dev=true&minify=false:4610:11
setDate@http://10.0.3.2:8081/index.bundle?platform=android&dev=true&minify=false:118736:25
resolve@http://10.0.3.2:8081/index.bundle?platform=android&dev=true&minify=false:128849:19
tryCallOne@http://10.0.3.2:8081/index.bundle?platform=android&dev=true&minify=false:26986:16
http://10.0.3.2:8081/index.bundle?platform=android&dev=true&minify=false:27087:27
_callTimer@http://10.0.3.2:8081/index.bundle?platform=android&dev=true&minify=false:30541:17
_callImmediatesPass@http://10.0.3.2:8081/index.bundle?platform=android&dev=true&minify=false:30577:19
callImmediates@http://10.0.3.2:8081/index.bundle?platform=android&dev=true&minify=false:30796:33
callImmediates@[native code]
__callImmediates@http://10.0.3.2:8081/index.bundle?platform=android&dev=true&minify=false:2561:35
http://10.0.3.2:8081/index.bundle?platform=android&dev=true&minify=false:2338:34
__guard@http://10.0.3.2:8081/index.bundle?platform=android&dev=true&minify=false:2544:15
flushedQueue@http://10.0.3.2:8081/index.bundle?platform=android&dev=true&minify=false:2337:21
flushedQueue@[native code]
invokeCallbackAndReturnFlushedQueue@[native code]

import React, { Component } from 'react';
import {
  View,
  Text,
  FlatList,
  TouchableWithoutFeedback,
  TouchableOpacity,
  Dimensions,
  Platform,
  TextInput,
  Image,
} from 'react-native';

import AsyncStorage from '@react-native-community/async-storage';
import Icon from 'react-native-vector-icons/FontAwesome5';
import { TextInputMask } from 'react-native-masked-text';
import ReactoTron from 'reactotron-react-native';

import PropTypes from 'prop-types';

import DateTimePicker from '@react-native-community/datetimepicker';

import moment from 'moment';
import Header from '~/components/Header';
// import ListItem from '~/components/ListItem';
import styles from './styles';
import { colors } from '~/styles';
import { data } from '~/components/Data';

AsyncStorage.clear();

const { width } = Dimensions.get('window');
const thumbnailWidth = 90;
const columnCount = Math.floor(width / thumbnailWidth);
const gutter = (width - columnCount * thumbnailWidth) / (columnCount * 2);

export default class Events extends Component {
  static propTypes = {
navigation: PropTypes.shape({
  navigate: PropTypes.func,
}).isRequired,
  };

  static navigationOptions = {
title: 'Eventos',
tabBarIcon: ({ tintColor }) => <Icon name="clock" size={20} color={tintColor} />,
tabBarPosition: 'bottom',
swipeEnabled: true,
animationEnabled: true,
initialLayout: undefined,
  };

  // constructor(props) {
  //   super(props);
  //   this.state = {
  //     date: moment,
  //   };
  // }

  state = {
dt: '',
date: new Date(),
prevDate: '',
maxDate: new Date(),
mode: 'date',
show: false,
data: [
  {
    id: 0,
    type: 'cashier',
    color: colors.blue,
    icon: 'cash-register',
    title: data.caixa.title,
    subTitle: 'Saldo Final: R$300',
    datetime: '23/07 19:01',

    cashier: {
      user: data.caixa.cashier.user,
      fundCash: '100,00',
      dateInit: '23/07/2019',
      timeInit: '08:00',
      dateEnd: '23/07/2019',
      timeEnd: '19:01',
    },
  },
  {
    id: 1,
    type: 'sale',
    color: colors.green,
    icon: 'shopping-cart',
    title: 'R$ 17,50 vendido por Administrador',
    subTitle: '1x Coca cola, 2x Cerveja brahma',
    datetime: '25/07 18:55',

    sale: {
      seller: 'Administrador',
      client: 'Fulano da Silva Sauro',
      detail: 'Vendeu 2 itens',
      total: 'R$ 17,50',

      items: [
        {
          id: 1,
          description: 'Coca-cola',
          amount: '1',
          price: '5,50',
          discount: '0,00',
          total: '5,50',
        },
        {
          id: 2,
          description: 'Cerveja brahma',
          amount: '1',
          price: '15,00',
          discount: '3,00',
          total: '12,00',
        },
      ],

      payments: [
        {
          id: 1,
          description: 'Dinheiro',
          total: '12,00',
        },
        {
          id: 2,
          description: 'Cartão Débito',
          total: '5,50',
        },
      ],
    },
  },
  {
    id: 2,
    type: '',
    color: colors.red,
    icon: 'archive',
    title: 'Acabou cerveja',
    subTitle: 'Fim estoque',
    datetime: '23/07 18:50',
  },
  {
    id: 3,
    type: 'sale',
    color: colors.green,
    icon: 'shopping-cart',
    title: 'R$ 89,00 vendido por Administrador',
    subTitle: '10x Cerveja, 2x Redbull, 1x cachaça',
    datetime: '23/07 18:50',

    sale: {
      seller: 'Administrador',
      client: 'Ana Baiana Meleva Daqui Pratinhos',
      detail: 'Vendeu 3 itens',
      total: 'R$ 89,00',

      items: [
        {
          id: 1,
          description: 'Cerveja Skoll',
          amount: '10',
          price: '5,50',
          discount: '0,00',
          total: '55,00',
        },
        {
          id: 2,
          description: 'Redbull',
          amount: '2',
          price: '12,00',
          discount: '0,00',
          total: '24,00',
        },
        {
          id: 3,
          description: 'Cachaça 51',
          amount: '1',
          price: '10,00',
          discount: '0,00',
          total: '10,00',
        },
      ],
      payments: [
        {
          id: 2,
          description: 'Cartão Débito',
          total: '89,00',
        },
      ],
    },
  },
  {
    id: 4,
    type: 'productStock',
    color: colors.yellow,
    icon: 'archive',
    title: 'Cerveja acabando',
    subTitle: 'Estoque atual: 10',
    datetime: '23/07 18:40',
    productStock: {
      minStock: 10,
      maxStock: 30,
      stock: 20,
    },
  },
  {
    id: 5,
    type: 'sale',
    color: colors.green,
    icon: 'shopping-cart',
    title: 'R$2,00 vendido por Beltrano',
    subTitle: '1x Caixa Bombom Nestle',
    datetime: '23/07 18:30',

    sale: {
      seller: 'Beltrano',
      client: 'Não informado',
      detail: 'Vendeu 1 item',
      total: 'R$ 5,00',

      items: [
        {
          id: 1,
          description: 'Caixa bombom Nestle',
          amount: '1',
          price: '5,00',
          discount: '0,00',
          total: '5,00',
        },
      ],
      payments: [
        {
          id: 1,
          description: 'Cartão Débito',
          total: '5,00',
        },
      ],
    },
  },
  {
    id: 6,
    type: 'sale',
    color: colors.green,
    icon: 'shopping-cart',
    title: 'R$2,00 vendido por Fulano',
    subTitle: '1x Pirulito',
    datetime: '23/07 18:00',

    sale: {
      seller: 'Fulano',
      client: 'Não informado',
      detail: 'Vendeu 1 item',
      total: 'R$ 2,00',

      items: [
        {
          id: 1,
          description: 'Pirulito',
          amount: '1',
          price: '2,00',
          discount: '0,00',
          total: '2,00',
        },
      ],
      payments: [
        {
          id: 1,
          description: 'Dinheiro',
          total: '5,00',
        },
      ],
    },
  },
  {
    id: 7,
    type: 'sale',
    color: colors.green,
    icon: 'shopping-cart',
    title: 'R$25,00 vendido por Fulano',
    subTitle: '1x Sorvete Kibom Chocolate',
    datetime: '23/07 17:20',

    sale: {
      seller: 'Fulano',
      client: 'Não informado',
      detail: 'Vendeu 1 item',
      total: 'R$ 25,00',

      items: [
        {
          id: 1,
          description: 'Sorvete Kibom Chocolate',
          amount: '1',
          price: '25,00',
          discount: '0,00',
          total: '25,00',
        },
      ],
      payments: [
        {
          id: 1,
          description: 'Dinheiro',
          total: '25,00',
        },
      ],
    },
  },
  {
    id: 8,
    type: 'sale',
    color: colors.green,
    icon: 'shopping-cart',
    title: 'R$15,00 vendido por Fulano',
    subTitle: '3x Bolacha Choc. Balduco',
    datetime: '23/07 15:00',

    sale: {
      seller: 'Fulano',
      client: 'Não informado',
      detail: 'Vendeu 1 item',
      total: 'R$ 15,00',

      items: [
        {
          id: 1,
          description: 'Bolacha Choc. Balduco',
          amount: '3',
          price: '5,00',
          discount: '0,00',
          total: '15,00',
        },
      ],
      payments: [
        {
          id: 1,
          description: 'Dinheiro',
          total: '15,00',
        },
      ],
    },
  },
  {
    id: 9,
    type: 'sale',
    color: colors.green,
    icon: 'shopping-cart',
    title: 'R$3,00 vendido por Beltrano',
    subTitle: '1x Chocolate Diamante Negro',
    datetime: '23/07 13:00',

    sale: {
      seller: 'Beltrano',
      client: 'Não informado',
      detail: 'Vendeu 1 item',
      total: 'R$ 5,00',

      items: [
        {
          id: 1,
          description: 'Diamante Negro',
          amount: '1',
          price: '3,00',
          discount: '0,00',
          total: '3,00',
        },
      ],
      payments: [
        {
          id: 1,
          description: 'Dinheiro',
          total: '3,00',
        },
      ],
    },
  },
  {
    id: 10,
    type: 'sale',
    color: colors.green,
    icon: 'shopping-cart',
    title: 'R$15,00 vendido por Fulano',
    subTitle: '1x Caixa de brinquedos',
    datetime: '23/07 12:10',

    sale: {
      seller: 'Fulano',
      client: 'Não informado',
      detail: 'Vendeu 1 item',
      total: 'R$ 15,00',

      items: [
        {
          id: 1,
          description: 'Caixa de brinquedos',
          amount: '1',
          price: '15,00',
          discount: '0,00',
          total: '15,00',
        },
      ],
      payments: [
        {
          id: 1,
          description: 'Dinheiro',
          total: '15,00',
        },
      ],
    },
  },
  {
    id: 11,
    type: '',
    color: colors.red,
    icon: 'archive',
    title: 'Acabou Caixa Bombom Garoto',
    subTitle: 'Fim estoque',
    datetime: '23/07 10:40',
  },
  {
    id: 12,
    type: 'sale',
    color: colors.green,
    icon: 'shopping-cart',
    title: 'R$5,00 vendido por Fulano',
    subTitle: '1x Caixa Bombom Garoto',
    datetime: '23/07 10:40',

    sale: {
      seller: 'Fulano',
      client: 'Amável Pinto',
      detail: 'Vendeu 1 item',
      total: 'R$ 5,00',

      items: [
        {
          id: 1,
          description: 'Caixa bombom Garoto',
          amount: '1',
          price: '5,00',
          discount: '0,00',
          total: '5,00',
        },
      ],
      payments: [
        {
          id: 1,
          description: 'Dinheiro',
          total: '5,00',
        },
      ],
    },
  },
  {
    id: 13,
    type: 'productStock',
    color: colors.yellow,
    icon: 'archive',
    title: 'Caixa bombo Garoto acabando',
    subTitle: 'Estoque atual: 1',
    datetime: '23/07 10:20',
  },
  {
    id: 14,
    type: 'cashier',
    color: colors.blue,
    icon: 'cash-register',
    title: 'Caixa Aberto por Fulano',
    subTitle: 'Saldo Inicial: R$100',
    datetime: '23/07 07:00',

    cashier: {
      user: 'Administrador',
      fundCash: '100,00',
      dateInit: '23/07/2019',
      timeInit: '08:02',
      dateEnd: '',
      timeEnd: '',
    },
  },
],
  };

  // DatePicker functions

  // FIXME: ERROR ON CANCEL
  setDate = (event, date) => {
// this.prevDate = moment().format();
this.prevDate = moment().format();
date = date || this.date;

ReactoTron.log('prevdate state', this.prevDate);
ReactoTron.log('data state', this.date);
ReactoTron.log('datalocal', date);

if (date === undefined) {
  this.setState({
    date: this.prevDate,
  });
}

this.setState({
  show: Platform.OS === 'ios',
  date,
});

if (date !== undefined) {
  this.setState(this.prevDate = date);
}
  }

  show = (mode) => {
this.setState({
  show: true,
  mode,
});
  }

  datepicker = () => {
this.show('date');
  }

  renderEventItem = (item) => {
const { navigation } = this.props;

const { type } = item;

if (type === 'cashier') {
  navigation.navigate('Cashier', { item });
} else if (type === 'sale') {
  navigation.navigate('Sale', { item });
} else if (type === 'productStock') {
  navigation.navigate('ProductStock', { item });
}
  };

  onShowArrow = (item) => {
if (item.type !== '') return <Icon name="angle-right" size={15} color="#e0e0e0" style={styles.iconArrow} />;
return null;
  };

  formatDate() {
const { date } = this.state;
// if (date === undefined) {
//   date = moment().format();
// }

const day = date.getDate();
const month = date.getMonth();
const year = date.getFullYear();
return `${day}/${month}/${year}`;
ReactoTron.log('FORMATDATE');
ReactoTron.log(`${day}/${month}/${year}`);
  }

  renderItem = ({ item }) => (
<TouchableWithoutFeedback
  onPress={() => {
    this.renderEventItem(item);
  }}
>
  <View style={[styles.listItem, { borderLeftColor: item.color }]}>
    <View style={styles.iconContainer}>
      <Icon name={item.icon} color={item.color} size={25} />
    </View>
    <View style={styles.centerContainer}>
      <Text style={{ fontSize: 12 }}>{item.title}</Text>
      <Text style={{ fontSize: 12 }}>{item.subTitle}</Text>
    </View>
    <View style={styles.rightContainer}>
      <View>
        {/* <Text style={styles.textHour}>{item.datetime.substring(5, 11)}</Text> */}
        <Text style={styles.textHour}>{item.datetime.substring(5, 11)}</Text>
      </View>

      <View style={{ flex: 1 }}>{this.onShowArrow(item)}</View>
    </View>
  </View>
</TouchableWithoutFeedback>
  );

  render() {
const {
  show, date, mode, dt, maxDate,
} = this.state;

return (
  <View>
    <Header title="Eventos" />
    <View style={styles.containerDate}>
      <TouchableOpacity style={styles.buttonCalend} onPress={this.datepicker}>
        <Image style={styles.btnIcon} source={require('../../images/date_icon.png')} />
        <Text style={styles.textDateFilter}>{this.formatDate()}</Text>
      </TouchableOpacity>
      { show && (
      <DateTimePicker
        value={date}
        mode={mode}
        maximumDate={maxDate}
        display="default"
        onChange={this.setDate}
        onConfirm={this.handleDatePicked}
      />
      )
    }
    </View>

    <FlatList
      style={styles.flatList}
      contentContainerStyle={styles.list}
      data={this.state.data}
      renderItem={this.renderItem}
      keyExtractor={item => item.id.toString()}
    />
  </View>
);
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

  • impossible to verify this code.

1 answer

0


The problem is described in the Warning itself

Invariant Violation: setState(...): takes an Object of state variables to update or a Function which Returns an Object of state variables.

That is, you are not sending an object or a function that returns a state object. This occurs in two parts of your code:

if (date === undefined) {
  this.setState(
    this.date = this.prevDate,
  );
}

...

if (date !== undefined) {
  this.setState(this.prevDate = date);
}

The correct thing in such cases would be to fill in an object, not the assignment. Otherwise, you are not working with the values of the state, to access one of its values must be done this.state.valorDesejado. For example, on the date of the state, it would be this.state.date. Already to correct the problem of assignments, the correct would be:

if (date === undefined) {
  this.setState({
    date: this.state.prevDate,
  });
}

That should solve some of your problems.

  • making only this change appears a typeError: ______________________________________________ WARN Possible Unhandled Promise Rejection (id: 0): &#xA;TypeError: date.getDate is not a function. (In 'date.getDate()', 'date.getDate' is&#xA;undefined)

  • another problem is that prevDate is a string, not a Date, then she doesn’t have the function getDate

  • 1

    I changed everyone where there is this.date or this.prevDate adding this.state, before this change was already working, but kept giving that Warning, now it’s ok, is only giving some problems of Eslint

Browser other questions tagged

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