React hook useState not updating the UI when using JavaScript Date object on setState

Viewed 1001

I have created a date object using React hook useState like this:

  const [selectedDate, setselectedDate] = useState(new Date());

I have a function that updates that object's day:

  const handleDayChange = (increment) => {
    let dateWillUpdate = selectedDate;
    date.setDate(selectedDate.getDate() + increment);
    setselectedDate(dateWillUpdate);
  };

The object is updated but the UI is not. So I tried another way which is to assign the date object like this:

let dateWillUpdate = {...selectedDate};

But this gives me an empty object:

object:{}

I am rendering the date with this function:

const renderDaySelector = () => {
    return (
      <View style={styles.selector}>
        <View style={[styles.fieldContainer, { flex: 1 }]}>
          <TouchableOpacity onPress={() => handleDayChange(1)}>
            <MaterialCommunityIcons
              name="chevron-up"
              color={Colors.primary}
              size={30}
            />
          </TouchableOpacity>
          <View style={[styles.field]}>
            <TextInput
              style={styles.textField}
              keyboardType="number-pad"
              value={selectedDate.getDate().toString()}
            />
          </View>
         ...
    );
  };

which I call in the main return of the function component:

return (
...

            <View style={styles.values}>{renderDaySelector()}</View>


...
)

How can I get the UI to update when calling the

handleDayChange()

function? Thanks.

1 Answers

You should not mutate your state directly. In this case you need to create a new Date object in order to properly update your state.

You can try using new Date() to create a new object as:

let dateWillUpdate = new Date(selectedDate)

// or you use:
let dateWillUpdate = new Date(selectedDate.getTime())
Related