0

I'm using two different states in my Form component. One to capture all the text inputs and one to capture the Date using the DatePicker component from Material UI.

I want to add a date state in my main input and update it based on the date state.

Here's the code that I'm using:

const [date, setDate] = useState(null);
const [inputValues, setInputValues] = useState({
  title: "",
  category: "",
  description: "",
  city: "",
  venue: "",
  date: "",
});

const handleChange = (event) => {
  setInputValues({
    ...inputValues,
    [event.target.name]: event.target.value,
    date: date,
  });
};

<TextField
  variant="outlined"
  label="Event title"
  size="small"
  fullWidth
  name="title" // name references the 'input' element attribute
  value={inputValues.title} // value references the 'input' attribute 'value'
  onChange={handleChange} // onChange will pass the event by default
></TextField>
<DatePicker
  value={date} // DatePicker requires onChange and value
  onChange={(newDate) => setDate(newDate)} // Cannot be set at the TextField level
  renderInput={(params) => (
    <TextField
      {...params}
      size="small"
      fullWidth
      variant="outlined"
    ></TextField>
  )}
></DatePicker>

Not sure if I need to use useEffect to link the two states together? Any guidance would be greatly appreciated.

Thanks!

jsejcksn
  • 27,667
  • 4
  • 38
  • 62
mrahma04
  • 109
  • 1
  • 6

1 Answers1

0

Instead of trying to update the date at the same time the other inputs are changed, do that in an effect that will take care of it automatically every time the date is updated by including it in the dependency array of the effect.

You should also use the functional form of the argument to setState (setInputValues in your code) when combining existing state data with new state data, to guarantee that you aren't setting stale data.

e.g.

  • This: setState(state => ({...state, someNewValue}))
  • Instead of: setState({...state, someNewValue})

Code in TypeScript Playground

import {useEffect, useState} from 'react';

function Component () {
  const [date, setDate] = useState(null);

  const [inputValues, setInputValues] = useState({
    title: "",
    category: "",
    description: "",
    city: "",
    venue: "",
    date: "",
  });

  useEffect(() => {
    if (typeof date !== 'string') return;
    setInputValues(state => ({...state, date}));
  }, [date]);

  const handleChange = (event) => {
    setInputValues(state => ({
      ...state,
      [event.target.name]: event.target.value,
    }));
  };

  // Rest of component...
}

jsejcksn
  • 27,667
  • 4
  • 38
  • 62