Skip to content
Advertisement

Is it bad practice to accept setState as a function parameter in React?

Basically, before uploading an image to the firebase, I’m trying to control the input as:

export const controlThumbnail = (selectedThumbnail, setThumbnailError) => {
  if (!selectedThumbnail) {
    setThumbnailError('Please select a thumbnail!');

    return;
  }

  if (!selectedThumbnail.type.includes('image')) {
    setThumbnailError('Please select an image!');

    return;
  }

  if (selectedThumbnail.size > 1000000) {
    setThumbnailError('Image size must be less than 1MB!');

    return;
  }

  setThumbnailError(null);
};

which I call the above method from /lib/controlThumbnail.js to:

import { controlThumbnail } from '../../lib/controlThumbnail';
    
const Signup = () => {
  const [userInfo, setUserInfo] = useState({
    name: '',
    email: '',
    password: '',
    thumbnail: null
  });
  const [thumbnailError, setThumbnailError] = useState(null);


  const userInputHandler = (e) => {
    setUserInfo((prevUserInfo) => {
      if (e.target.name === 'thumbnail') {
        const thumbnail = e.target.files[0];
        controlThumbnail(thumbnail, setThumbnailError);

        return { ...prevUserInfo, thumbnail };
      } else {
        return { ...prevUserInfo, [e.target.name]: e.target.value };
      }
    });
  };
...

so, this is now works correctly, but I wonder if this is the good way of doing it? Or should I put the control method inside the component and never give setState as parameter?

Advertisement

Answer

It is subjective. Personally, I think the controlThumbnail function is not the right place to make that abstraction. In here, you are really only providing validation. You don’t need to give it the responsibility to validate AND set some state.

You could create a pure validation function, and just use the return of this to update the state in your Signup component:

const validateThumbnail = (thumbnail) => {
  if (!thumbnail) {
    return 'Please select a thumbnail!';
  }

  if (!thumbnail.type.includes('image')) {
    return 'Please select an image!'
  }

  if (thumbnail.size > 1000000) {
    return 'Image size must be less than 1MB!'
  }

  return null
}

const Signup = () => {
  const [userInfo, setUserInfo] = useState({
    name: '',
    email: '',
    password: '',
    thumbnail: null
  });
  const [thumbnailError, setThumbnailError] = useState(null);


  const userInputHandler = (e) => {
    setUserInfo((prevUserInfo) => {
      if (e.target.name === 'thumbnail') {
        const thumbnail = e.target.files[0];
        setThumbnailError(validateThumbnail(thumbnail));
        return { ...prevUserInfo, thumbnail };
      }
      return { ...prevUserInfo, [e.target.name]: e.target.value };
    });
  }
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement