Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 67469

How to pass an input target value and setState values as parameters for a helper function?

$
0
0

I have a function that looks like this, it takes an input file and posts it to the backend:

const loadFile = async ({ target }) => {
    const file = target.files[0];

    if (file) {
      const { name, size } = file;

      // TODO: CHANGE URL
      if (size > 5000000) {
        setIsUploadError('File size too big');
      } else {
        const res = await PostData(`${BACKEND_ADDRESS}/${UPLOAD_ENDPOINT}`, file, userId, isUploading, uploadError);
        if (res) {
          if (res.status === 200) {
            const resJson = await res.json();

            const newUpload = {
              id: resJson.id,
              upload: {
                id: resJson.upload_id,
                title: name,
                url: resJson.url,
              },
            };
            setIsUploadLoading(false);
          } else if (res.status === 500) {
            setIsUploadError('Error uploading');
          }
        }
      }
    }
  };
<input
  type="file"
  id="buttonUpload"
  onChange={loadFile}
/>

Tried to move it to a helper function file, add the postData() function it uses also there and then import it and call it something like this:

loadFile(userId, target, setIsUploadError);

Can't get it to work:

Error: target is not defined

How to get the target file passed as parameter from the input? Is it ok to pass the hooks setState values (setIsUploadError) just like that?

UPDATE: Thanks, now the input file passes the file, solution provided in the comments as:

onChange={e => loadFile({
    userId, target: e.target, setIsUploadLoading, setIsUploadError,
})}

Now I struggle on passing the setState values. The postData function called inside the loadFile should take parameters via loadFile function and looks looks like this:

export const PostData = async (url = '', data = {}, userId, isUploading, uploadError) => {
  isUploading(true);
  const formData = new FormData();
  formData.append('file', data);
  formData.append('userId', userId);
  formData.append('pdf_form', 'PDF_FORM');

  try {
    const result = await fetch(url, {
      method: 'POST',
      mode: 'cors',
      cache: 'no-cache',
      credentials: 'same-origin',
      headers: {},
      redirect: 'follow',
      referrer: 'no-referrer',
      body: formData,
    });

    return result;
  } catch (e) {
    uploadError(e.message);
    return false;
  }
};
Error: Uncaught (in promise) TypeError: isUploading is not a function

Viewing all articles
Browse latest Browse all 67469

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>