简体   繁体   中英

async function has old state React-Redux

I am working on a React project where user can upload and remove photos in projects. After Uploading new image it should be visible to user only if corresponding projectis selected. The solution is fairly simple to check

if 
(selectedProject.projectID=== imageMetadata.projectID)

where

  • selectedProject.projectID: Id of currently selected project( Comming from Redux Store )
  • imageMetadata.projectID: Id of project to which uploaded image belongs.

All of this is being done inside an async function and the problem we are facing is that even after selectedAlbum.albumID is changed everywhere else, this function still has its old value. Is it because the function is async?

This is my code:

 let projectId = selectedProject.projectID;
 const responses = await Promise.all(
   filesToUpload.map( async (file) => {
     let res = await imageStoreApiHandler.uploadPhoto(file, projectId);
     notifyUploadProgress(count++, total, notifcationKey);
     if (res.status === 200) {
       let imageMetadata: any = res.data[0];
       if (selectedProject.projectID === imageMetadata.projectID) {
         addImage(imageMetadata);
       }
     }
     return res;
   }));

It's probably a closure problem where the uploadhandler keeps caching the first function.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Maybe write a function which will return a promise all array based on the parameters current project id.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM