Search code examples
javascriptreactjsuse-effect

UseEffect stop working after refreshing the site


I'm working in ReactJS. I have a form that is suppossed to be the configuration of another form. This specif form kind of looks like this:

  const [startingDate, setStartingDate] = useState();
  const [endingDate, setEndingDate] = useState();
  const [startingTime, setStartingTime] = useState();
  const [endingTime, setEndingTime] = useState();
  const [places, setPlaces] = useState();

  const createConfig = () => {
    Axios.post("http://localhost:3005/adminConfig", {
      startingDate,
      endingDate,
      startingTime,
      endingTime,
      places,
      organization: user._id,
    }).then((response) => {
      alert("successful")
    })
  }

After you send that data to the server I'm supposed to retrieve and set it as the configuration of another form (This second form is supposed to be shared and filled by other people) in the next way:

const [config, setConfig] = useState([]);

  useEffect(() => {
    Axios.get(`http://localhost:3005/adminConfig/`).then((response) => {
      setConfig(response.data);
    });
  }, []);

          <input
            type="date"
            placeholder="Date of the meeting
            name="date"
            id="datePickerId"
            min={config[0].startingDate}
            max={config[0].endingDate}
            onChange={(event) => {
              setDate(event.target.value);
            }}
            required
          />

When you access this form and havent set the configuration in React it works good. After accessing it and starting the configuration you can see how it updates; the dates are limited and in theory everything works good, the problem comes when you refresh the site or someone else try to access, it stops working and you have to delete the settings (config[0].startingDate, etc)

console shows:

Cannot read properties of undefined (reading 'startingDate')

Any help is appreciated


Solution

  • The useEffect hook is executed after the page is loaded. and at the time of initial page loading, config[0] is not defined.

    use optional chaining and default value togther:

    <input
        type="date"
        placeholder="Date of the meeting"
        name="date"
        id="datePickerId"
        min={config[0]?.startingDate || 0} // <==  
        max={config[0]?.endingDate || 0} // <==
        onChange={(event) => {
            setDate(event.target.value);
        }}
        required
    />