Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react-native error : value for date cannot be cast from string to double

So, I have this reminder component with textInput being imported from react-native and DatePicker being imported from the native base and a button which will save the form on click event.

now when I click on the datepicker, it gives an error saying: value for date cannot be cast from string to double. I have also attached a screenshot of the error.

Error screenshot

not sure where I am going wrong.

this is the component's code.

class Reminder extends Component {

    constructor(props) {
        super(props);
        let formatDate = new Date();
        this.state = {
            chosenDate: formatDate.toISOString().split('T')[0],
            text: '',
        };
        this.handleChangeInput = this.handleChangeInput.bind(this);
        this.saveData = this.saveData.bind(this);
    }


    render() { 
        const {chosenDate} = this.state;
        return ( 
            <View>
                <Form style={styles.formContainer}>
                    <View style={styles.formView}>

                        < TextInput
                            placeholder = "Set your reminder"
                            onChangeText={this.handleChangeInput}
                            value={this.state.text}
                        />

                        <DatePicker
                            defaultDate={chosenDate}
                            mode = "date"
                            animationType={"fade"}
                            androidMode={"default"}
                            placeHolderText="Select date"
                            textStyle={{ color: "green" }}
                            placeHolderTextStyle={{ color: "#d3d3d3" }}
                            onDateChange={(chosenDate) => this.setState({chosenDate})}
                        />
                        <Text style={styles.datePicker}>
                            {chosenDate}
                        </Text>
                    </View>
                    <View style={styles.footer}>
                        <Button block success style={styles.saveBtn} 
                            onPress={ () => 
                                    {
                                    this.saveData()
                                    //console.log('save data', fomattedState);
                                    Alert.alert('Yay!!', 'Succefully saved.')
                                    }
                                } 
                           >
                            <Icon type='MaterialIcons' name='done' />                        
                        </Button>
                    </View>
                </Form>
            </View> 
        );
    }

    handleChangeInput = (input) => {
        this.setState({
            text: input
        });
    }

    //save the input
    saveData() {
        let {chosenDate, ...restOfState} =  this.state;
        let textArray = Object.entries(restOfState).map(([key, value])=> ({[key]: value}));
        let fomattedState = {[chosenDate]:textArray};
        console.log('formatted state', fomattedState);
        AsyncStorage.setItem("key", JSON.stringify(this.fomattedState));
    }
}
like image 402
Nauman Tanwir Avatar asked Dec 10 '18 18:12

Nauman Tanwir


3 Answers

I had the same issue in this @react-native-community/datetimepicker package. So I fixed this issue with the Moment library and JavaScript Date.parse() method:

const [targetDate, setTargetDate] = useState(
    new Date(
      Date.parse(
        moment(selectedGoal.targetDate, 'DD/MM/YYYY').format(
          'ddd MMM DD YYYY HH:mm:ss ZZ',
        ),
      ),
    ),
  );
like image 63
tapu74 Avatar answered Nov 13 '22 12:11

tapu74


The error is most likely due to the default date field you are providing. You are sending a string. Try setting the default date like this like specified in Native Base documentation http://docs.nativebase.io/Components.html#date-picker-def-headref:

<DatePicker
            defaultDate={new Date(2018, 4, 4)}
            locale={"en"}
            modalTransparent={false}
            animationType={"fade"}
            androidMode={"default"}
            placeHolderText="Select date"
            textStyle={{ color: "green" }}
            placeHolderTextStyle={{ color: "#d3d3d3" }}
            onDateChange={this.setDate}
            />

If that works you should then parse the date stored in chosenDate in the state and send the parameters like the example I provided....

let dateNumbers = this.state.chosenDate.split('-');  

and then you have year, date and month

(3) ["2018", "12", "10"]

and you can parse it as int each part then you have what you need to set the default date:

  <DatePicker
                defaultDate={new Date(parseInt(dateNumbers[0]), parseInt(dateNumbers[1]),parseInt(dateNumbers[2]))}
                locale={"en"}
                modalTransparent={false}
                animationType={"fade"}
                androidMode={"default"}
                placeHolderText="Select date"
                textStyle={{ color: "green" }}
                placeHolderTextStyle={{ color: "#d3d3d3" }}
                onDateChange={this.setDate}
                />
like image 3
Juan Avatar answered Nov 13 '22 11:11

Juan


Also same issue using @react-native-community/datetimepicker with Android (iOS was working fine). In my case, I solved it this way:

1) State variables:

const [isPickerOpen, setIsPickerOpen] = useState(false);
const user = useSelector(state => state.user); // Using Redux to store User's birthday
const parsedBirthday = new Date(moment(user.birthday).format('YYYY-MM-DD'));
const [birthday, setBirthday] = useState(parsedBirthday);

2) Show TextInput and Picker:

<TouchableOpacity onPress={() => showDatepicker()}>
    <TextInput
        style={styles.inputText}
        editable={false}
        pointerEvents='none'
        onTouchStart={() => { showDatePicker() }}
        value={moment(birthday).format('DD-MM-YYYY')}
    />
</TouchableOpacity>
{(isPickerOpen) ?
    <View>
        <DatePicker
            minimumDate={new Date(1901, 0, 1)}
            maximumDate={new Date()}
            value={birthday}
            mode='date'
            display='default'
            onChange={datePickerHandler} 
        />
    </View>
 : null
}

3) Handlers:

const showDatePicker = () => {
    setIsPickerOpen(true);
}

const datePickerHandler = (event, selectedDate) => {
    const currentDate = selectedDate || birthday;
    if (Platform.OS === 'android') setIsPickerOpen(false);
    setBirthday(currentDate);
}
like image 2
Sergi Juanati Avatar answered Nov 13 '22 11:11

Sergi Juanati