0

i'm trying to create delete button that delete a group of objects instead of one object, but the axios request don't work inside the forEach loop.

function handleClick(e) {
            cont GetByName = axios.get('my/api/link').filter(i => i.mylist === `${name}`)
            GetByName.forEach(i => axios.delete('my/api/link'+i.id))
      }

Please Note: I didn't add .then(res=>consolse.log(res) just to make it make it brief.

Also note: that using console.log instead of axios.delete is working very fine.

Maybe I can explain my problem in another approach

const [Id,setId] = useState(null)
function handleClick(e) {
            cont GetByName = axios.get('my/api/link').filter(i => i.mylist === `${name}`)
            GetByName.forEach(i => setId(i.id))
            console.log(Id)
      }

this console.log return null

Ali Husham
  • 816
  • 10
  • 31
  • 2
    `axios.get()` is **async** so you need to **await** to use the response array, if that's an array. – norbitrial Aug 20 '20 at 12:31
  • 1
    Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Heretic Monkey Aug 20 '20 at 12:32
  • I tried `GetByName.forEach(async (i )=> await axios.delete('my/api/link'+i.id)) ` but didn't work as well. – Ali Husham Aug 20 '20 at 12:42
  • You may want to create a "delete many" endpoint on your server vs looping an unknown amount of id's and deleting each one individually. – Yatrix Aug 20 '20 at 12:45
  • Maybe I can explain my problem in another approach ``` const [Id,setId] = useState(null) function handleClick(e) { cont GetByName = axios.get('my/api/link').filter(i => i.mylist === `${name}`) GetByName.forEach(i => setId(i.id)) console.log(id) } ``` this `console.log` return null for me – Ali Husham Aug 20 '20 at 12:50

1 Answers1

0

Solved using setTimeout(() => {}, 0))

function handleClick(e) {
            cont GetByName = axios.get('my/api/link').filter(i => i.mylist === `${name}`)
            GetByName.forEach(i => {
                setTimeout(() => {
                axios.delete('my/api/link'+i.id)  
            }, 0))
})
      }
Ali Husham
  • 816
  • 10
  • 31