0

I'm trying to make edits to a draft object from Immer that depend on a promise resolving. I understand how to do this with async/await syntax, (see below)

import produce from 'immer';

Promise.resolve({ eggs: 0 }).then(
  produce(async (eggCounter) => { const n = (await 5); eggCounter.eggs += n; })
).then(console.log)

but when I attempt to translate this into using the explicit Promise API, it does not work:

import produce from 'immer';

Promise.resolve({ eggs: 0 }).then(
  produce((eggCounter) => { Promise.resolve(5).then((n) => eggCounter.eggs += n) })
).then(console.log)

The above generates the error Uncaught (in promise) TypeError: illegal operation attempted on a revoked proxy.

How can I modify the second sample so that it is (sufficiently) equivalent to the first?

pixatlazaki
  • 572
  • 8
  • 19

1 Answers1

2

Just return a promise for produce callback function:

In-line version

Promise.resolve({ eggs: 0 }).then(
  produce((eggCounter) => Promise.resolve(5).then((n) => { eggCounter.eggs += n; }))
).then(console.log)

Clear version

Promise.resolve({ eggs: 0 }).then(
  produce((eggCounter) => {
    return Promise.resolve(5).then((n) => {
      eggCounter.eggs += n;
    });
  })
).then(console.log);
hoangdv
  • 15,138
  • 4
  • 27
  • 48
  • This is correct, though an important _other_ detail that I missed is that the function passed to the `then` call inside the `produce` callback must not return a value (otherwise immer complains that you're augmenting the draft _and_ returning a value. – pixatlazaki May 27 '21 at 17:09