'On submit send data to API by taking data from an array of objects in react

On submit I want to call a function and send data as object of key value , taking data from an array of objects


const [documents,setDocuments] = useState({}); 

let selected= [
          {name: 'Profile', value:'S'}, 
          {name: 'Pan card', value:'P'},           
          {name: 'Document(Investment proof) ', value:'IP'}
         ]


function onSubmit(){

  selected.map(data=>setDocuments({...documents, [data.value]: data.value})) 
  axios.post(`api`, documents)

}

result should be like this: axios.post(api, {S:'S', P:'P', IP:'IP'})



Solution 1:[1]

useState and setState both are asynchronous. if you send object use reduce.

const obj = selected.reduce((pre,curr)=>{
   pre[curr.value] = curr.value
   return pre
 },{}) 

axios.post(`api`, obj)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yawei Li