-1

I have an array of items that I want to insert into the database one after another, something like this:

[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}] 

so basically, there would be a for..of loop iterating over this array and inserting them one after the another. I want to break out of the loop once an error happens, so for instance the error occurred after the 8th item:

[{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}] 
                                 ^: error here

So I want to stop the execution at this phase, how to implement this? my code looks like this:

const [createOneUser, { isLoading, isError, isSuccess, error }] = useCreateOneUserMutation()
const bulkUsers = [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}] 
const handleInsert = async()=>{
 for(const obj of bulkUsers){
    await createOneUser(obj) // <--- here
 }
}
return <button onClick={handleInsert}>start bulk insert</button>

this looks different from how we usually do the stuff using useEffect, but that's just a drafted plan to implement this. and I have no idea how to do this.

How to implement a similar logic in the redux toolkit query?

Normal
  • 1,616
  • 15
  • 39

1 Answers1

0

I was able to solve this problem by using the .unwrap() method of redux, unwrapping the mutation hook [0] given parameter returns a promise that you can await.

+ by default, if you have a loop of queries going into one end-point, redux will not execute the requests blindly quickly as the for loop loops, instead, it runs them one by one, therefore, if you have a logic similar to the one I had, you should .unwrap() then await your query to detect if it was failed or resolved.

const [createOneUser, { isLoading, isError, isSuccess, error }] = useCreateOneUserMutation()
const bulkUsers = [{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}] 
const handleInsert = async()=>{
 for(const obj of bulkUsers){
    try{
        await (createOneUser(obj).unwrap()) // <--- here
    }
    catch(error){
        // ... handle error logic here
    }
 }
}
return <button onClick={handleInsert}>start bulk insert</button>

Important: How to break out of an async for loop on button press in React

Special thanks to (markerikson)

https://github.com/reduxjs/redux-toolkit/discussions/2697#discussioncomment-3646116

Normal
  • 1,616
  • 15
  • 39