Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React wait for useEffect to finish before return

I feel bad for asking this kind of question but I have tried everything I could have done and I’m a bit lost with zero experience in React.
Here is the snippet:

export function FileUpload({
  file,
  url,
  onDelete,
  onUpload,
}: FileUploadProps) {
  const [progress, setProgress] = useState(0);
  useEffect(() => {
    async function upload() {
      url = await uploadFile(file, setProgress);
      console.log(url) //I need get this value on return
      onUpload(file, url);
    }
    upload();
  }, []);
  console.log(url) //empty string here
  return (
    <Grid item>
      <FileHeader file={file} url={url} onDelete={onDelete} />
      <LinearProgress variant="determinate" value={progress} />
    </Grid>
  );
}

The issue is I got url value empty before the return

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I believe you’re not using the url prop from the props, so lemme remove it and add url to state instead.

export function FileUpload({
  file,
  onDelete,
  onUpload,
}: FileUploadProps) {
  const [progress, setProgress] = useState(0);
  const [url, setUrl] = useState('');
  useEffect(() => {
    async function upload() {
      url = await uploadFile(file, setProgress);
      setUrl(url) // this will set the state variable
      onUpload(file, url);
    }
    upload();
  }, []);
  if (!url) { // checking for empty url here.
    return null;
  }

  return ( // This only gets returned when url is not empty
    <Grid item>
      <FileHeader file={file} url={url} onDelete={onDelete} />
      <LinearProgress variant="determinate" value={progress} />
    </Grid>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading