2
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?

Linda Paiste
  • 38,446
  • 6
  • 64
  • 102
jaeyoi
  • 61
  • 2

1 Answers1

0

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]
Carmine Tambascia
  • 1,628
  • 2
  • 18
  • 32