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

How to update an object all elements inside map function in react

I want to update object all elements one by one in map, It is updating only one element of the object not all

 const [docUrls, setDocUrls] = useState({
    imageUrl: "", panUrl: "",statementUrl: ""
  })

response from api

res.data.map(item=>{
          if(item.type === 'image'){
            setDocUrls({...docUrls, imageUrl:item.url})
          }else if(item.type  === 'pan'){
            setDocUrls({...docUrls, panUrl:item.url}) 
          }else                   
            setDocUrls({...docUrls, statementUrl:item.url})
          }})

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 :

setDocUrls is asynchronous so you’re just overwriting docUrls everytime you call it.

Having multiple setDocUrls({...docUrls, imageUrl:item.url}) will just keep overwriting the previous call due to the ...docUrls.

Instead, make a copy of docUrl.

const docUrlCopy = { ...docUrls }
res.data.map(item=>{
      if(item.type === 'image'){
        docUrlCopy.imageUrl = item.url

      }else if(item.type  === 'pan'){
        docUrlCopy.panUrl = item.url
      }else  
        docUrlCopy.statementUrl = item.url                 
      }})
setDocUrls(docUrlCopy) // only 1 call 
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