Lance
Lance

Reputation: 257

How to loop through an array with keys and values in to send a request for Axios.get's params in ReactJS?

I'm trying to implement a delete function where the user can select multiple files, then I will retrieve both the fileID and the deletedBy field. After mapping both fileID and deletedBy together, I will send them to this deleteFile function where in this case I need to send 3 axios get requests accordingly and individually to delete the function, but I just can't make the loop work.

   const deleteFile = async (file) => {
        const responses = [];
        const url = 'https://api.com/delete_file_web';

        for (let i = 0; i < file.length; i++) {
            responses.push(await axios.get(url, { params: {
                fileID: file.fileID,
                deletedBy: file.deletedBy
            }})
            )
        }

        Promise.all(responses)
        .then(response =>
            alert('File has been successfully deleted!')
        )
        .catch(err => console.error(err))
    };

enter image description here

Upvotes: 1

Views: 1007

Answers (1)

Danial
Danial

Reputation: 1643

Just use i in loop.

const deleteFile = (file) => {
    const requests = [];
    const url = 'https://api.com/delete_file_web';

    for (let i = 0; i < file.length; i++) {
        requests.push(axios.get(url, { params: {
            fileID: file[i].fileID,
            deletedBy: file[i].deletedBy
        }})
        )
    }

    axios.all(requests)
        .then((res) => {
            console.log(res);
        });
};

Upvotes: 1

Related Questions