nss-day-cohort-46 / How-to-Ask-for-Help

0 stars 0 forks source link

Bulk/multiple add/create objects #213

Closed CheoR closed 3 years ago

CheoR commented 3 years ago

Ticket MUST be completed before getting help from an instructor

Name: Cheo

Breakout Room: Hackery

Have you searched the other issue tickets? If not, do that first.

REQUIRED Add Tags to Issue Ticket and Assign to Project Board

REQUIRED Describe your issue:

I have a counter where user in/decrement the number of objects they want to create. On clicking Add button, app creates given number of objects.

REQUIRED Copy/paste any error messages that appear:

Seems like with -w, json-server creates the correct amount of objects, but throws warnings. without -w , json-server creates a random amount of objects or whatever number was last used the last time -w was used, but with no warnings.

image

REQUIRED What have you googled? (You must have at least 3 links related to your issue)

REQUIRED: What have you tried? Tell us everything you have tried.

For loops Promises Chaining requests (not useful since I don't know in advance how many objects the users wants created)

REQUIRED: Copy/paste link TO THE FILE on your branch that you are having issues with

Your link: Link

Code Snippet

Current workaround. Note errors received when using -w

  const location = useLocation()
  const callCreate = []
  for(let i=0; i <  num; i ++) {
   callCreate.push(createType.callAdd(createType.type))
  }
  Promise.all(callCreate).then(()=> { 
      console.log(`${num} objects created`)
   }).then(() => {
       history.push(location.pathname)
  })
CheoR commented 3 years ago

Similar SO issue. @ajawashington helped resolving issue.

Instead of calling function (with argument) inside an array

for(let i=0; i <  num; i ++) {
   callCreate.push(createType.callAdd(createType.type))
  }

just pass in function name with no parameter

for(let i=0; i <  num; i ++) {
   callCreate.push(createType.callAdd)
  }

then map through your array in Promise.all and apply your argument to it.

   Promise.all(createCalls.map(callback => callback(createType.type)))

CAVEAT

This approach will require calling json-server without the -w flag, else will still create objects but will also get the ERR_CONNECTION_REFUSED error noted above.

json-server -p 8088 database.json