David
David

Reputation: 39

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

Upvotes: 2

Views: 99

Answers (4)

Aidin53
Aidin53

Reputation: 733

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
/>

Upvotes: 1

Abdullah Ansari
Abdullah Ansari

Reputation: 710

You can use optional chaining to achieve the required behavior, The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

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

Upvotes: 0

manthankumbhar
manthankumbhar

Reputation: 15

Try making the axios request async too so that it doesn't return an empty array.

Upvotes: 0

StepUp
StepUp

Reputation: 38134

If it is possible, you can use fallback value:

min={ config?.length > 0 ? config[0].startingDate : '1980-01-17'}

The reason why you've got an error as some people do not have admin config and it is okay:

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

Upvotes: 0

Related Questions