immer - Nested produce calls are not working as expected

793 Views Asked by At
const { produce } = require("immer");

const outer = produce((draft) => {
  return inner(draft);
}, {});

const inner = produce((draft) => {
  draft.arr = [4, 5, 6];
}, {});

outer().arr.sort();
inner().arr.sort();

link: https://codesandbox.io/s/boring-wiles-ezqtr

There is an error on inner().arr.sort(). (read-only error)
My expectation is that outer().arr.sort() also be an error.
Is there something I'm doing wrong here?

1

There are 1 best solutions below

0
On

Not sure why you want an nested produce but as my understanding you are trying to write a function that leverage immer to sort an array so, to avoid changing initial array.

This is how you could go and from here use another "produce" function that does that. (Code Sandbox)

const { produce } = require("immer")

const baseArray = [6, 10, 3, 2, 1]
const baseArray2 = [17, 9, 10, 3, 2, 1];

function sortedF(state) {
  return produce(state, (draft) => {
    const sorted = draft.sort((a, b) => a - b)
    console.log(sorted);
  });
}

const sorted1 = sortedF(baseArray)
console.log(sorted1); // [1, 2, 3, 6, 10]

This use a carried solution curried-produce

const sortedCarried = produce((draft) => {
  const sorted2 = draft.sort((a, b) => a - b)
});

const sorted2 = sortedCarried(baseArray2)
console.log(sorted2); // [1, 2, 3, 9, 10, 17]