Home > Back-end >  Cannot access a function when is true in React
Cannot access a function when is true in React

Time:01-01

export const dateValid = (deadline, callback) => {
  const datediff = new Date(deadline).getTime() - Date.now();
  
  if(datediff < 1) callback(false)

}
  export const checkIfImage = (url, callback) => {
    const img = new Image();
    img.src = url;
  
    if (img.complete) callback(true);
  
    img.onload = () => callback(true);
    img.onerror = () => callback(false);
  };

I have created these two in an index.js. The checkIfImage is used to validate the image URL where the dateValid is to ensure the user selects the valid date. If the image URL does not exist or the deadline is not at least one day after the current date, the callback will be false. The image URL and deadline are the values that get from the users' input.

This code below is one of the functions in another file. I was expected the user have to fill in the input and it will get the image URL and deadline. After the user clicked submit button, the handleSubmit function will be called to check both of the inputs.

  const handleSubmit = async (e) => {
    e.preventDefault();

    checkIfImage(form.image, async (exists) => {
      if (exists) {
        dateValid(form.deadline, async (exists) => {
          if (exists) {
            console.log('date')
          } else {
            alert('End date must at least one day from today')
            setForm({ ...form, deadline: '' });
          }
        })
      } else {
        alert('Provide valid image URL')
        setForm({ ...form, image: '' });
      }
    })
  }

When the image URL or the date are invalid, both of the else statement can work properly but only when two of the inputs are valid, the console.log('date') part cannot be access. Do anyone know where I went wrong, thanks.

CodePudding user response:

Maybe try to log the second exists and form.deadline to see what's inside.

You can also change the name of your second exists to make sure it doesn't interfere with the first one.

And in your dateValid function a callback(true) is missing somewhere like :

export const dateValid = (deadline, callback) => {
  const datediff = new Date(deadline).getTime() - Date.now();
  
  if(datediff < 1) callback(false)
  else callback(true)

}
  • Related