Search code examples
reactjsreact-nativereact-modal

why i got [object object ]


import React, { Component } from "react";
import { Button, View ,Text ,StyleSheet, FlatList, ScrollView} from "react-native";
import DateTimePicker from "react-native-modal-datetime-picker";
import moment from 'moment'
import addDays from 'date-fns/addDays'
import Modal from 'react-native-modal';

export default class MExample extends Component {
  constructor(props) {
    super(props);
    this.state = {
      list: [],
      day:[],
      isDateTimePickerVisible: false,
      choseDate:'',
      visibleModal: false,
      lists:''
    };
  }


  showDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: true });
  };

  hideDateTimePicker = () => {
    this.setState({ isDateTimePickerVisible: false });
  };

  handleDatePicker = ( date ) => {
    // console.log("A date has been picked:", date); here date come correctly
    this.setState ({
      choseDate: 'Subscription start date ' + moment(date).format('MMMM, Do YYYY '),
    })
    this.hideDateTimePicker();
  };

  hideListPicker = () => {
    this.setState({ visibleModal: null ,list:[] });
  }; 

  handleListPicker = ( list ) => {
    console.log(list.toString()) 

    this.setState ({
      lists: 'list of start dates ' + list
    })
    this.hideListPicker();
  };

 
  getListViewItem = (item) => {
      let newList = this.state.list;
      if (newList.includes(item)) {
        let index = newList.indexOf(item);
        newList.splice(index,1);
        } else {
        newList.push(item);
      }
      this.setState({
        list: newList,
      });
 }

  renderModalContent = () => (
    <View>  
      <Text style={styles.textBox} onPress={this.showDateTimePicker}>Select Date</Text>    
        <DateTimePicker
          isVisible={this.state.isDateTimePickerVisible}
          onConfirm={this.handleDatePicker}
          onCancel={this.hideDateTimePicker}
          minimumDate = {new Date()}
          maximumDate = {addDays(new Date(), 30)}
            />
      
    <View style = {{backgroundColor:'white'}}>
            <View>
              <FlatList horizontal={true} 
                  data = {[{day: '1'},{day: '2'}, {day: '3'},{day: '4'}, {day: '5'},{day: '6'},{day: '7'}]}
                  renderItem={({item, index}) =>
                      <Text style={styles.textBox} key={index}
                            onPress={this.getListViewItem.bind(this, item.day)}>{item.day}
                      </Text>}
              />
              
                <ScrollView
                  style = {{marginHorizontal: 20}} 
                  horizontal={true}
                > 
                  {
                  this.state.list.map((l, index) => {
                      return(
                     index !== this.state.list.length - 1 ? <Text style={{fontSize:30, color:'red'}}>{l}, </Text> : <Text style={{fontSize:30, color:'red'}}>{l}</Text>
                      )
                    })
                  }
                </ScrollView>
                </View>
           </View>
      <Button
      onPress={this.handleListPicker}
        title="Submit"
      />
    </View>
  );

  render() {
     return (
        <>
       <Text style={{fontSize:20}}>Frequency</Text>
            <View style={styles.container} >
                <Text style={styles.textBox}  onPress={() => this.setState({ visibleModal: 'default' })}>Weekly </Text>
              </View>
              <Text style={{fontSize:20, color:'black', textAlign:'center'}}>{this.state.choseDate} </Text>
              <Text style={{fontSize:20, color:'black', textAlign:'center'}}>{this.state.lists} </Text>

           <Modal isVisible={this.state.visibleModal === 'default'} 
             onBackButtonPress={() => this.setState({ visibleModal: null, list:[] },  )}>
             {this.renderModalContent()}
           </Modal> 
         </>
    );
  }
}

const styles = StyleSheet.create({
  container:{
    flexDirection:'row', 
    flexWrap:'wrap',
    justifyContent:'center',
  },
  textBox :{
    fontSize:20,
    textAlign:'center',  
    borderWidth: 1,
    borderRadius: 12,
    borderColor: "#CBCBCB",
    margin:10,
    padding:5,
    backgroundColor:'#a0a3a3'
  },
});

i have created modal here user select date list and after submit i clear list in setState why i get [object object] in console

 export default class MExample extends Component {
   constructor(props) {
     super(props);
      this.state = {
         list: [],
         visibleModal: false,
         lists: ''
      };
    }

 hideListPicker = () => {
   this.setState({ visibleModal: null ,list:[] });
  }; 

 handleListPicker = ( list ) => {
  console.log(list.toString()) 
  // [object objcet]

  this.setState ({
     lists: 'list of start dates ' + list
   })
  this.hideListPicker();
 };

 render(){
   return( 
    // jsx <Text>{this.state.lists} </Text> // [object object]

   <Button onPress={this.handleListPicker}
    title="Submit"
  />
  )
}

Solution

  • Use JSON.stringify instead .toString This question might help you What's the difference in using toString() compared to JSON.stringify()? understand the difference

    let x = {a: 123, b: 321};
    console.log("toString", x.toString());
    console.log("stringified", JSON.stringify(x));

    If you're having a circular JSON you might like to visit How can I print a circular structure in a JSON-like format? to see how to console such JSONs