luisanton-io / recoil-nexus

MIT License
163 stars 13 forks source link

setRecoil fils to set object array sometimes #33

Closed javatlacati closed 3 months ago

javatlacati commented 3 months ago

Having two similar recoil states

export const employeesState: RecoilState<Employee[]> = atom({
  key: 'employeesState',
  default: [] as Employee[],
});

export const subsidiariesState: RecoilState<Subsidiary[]> = atom({
  key: 'subsidiariesState',
  default: [] as Subsidiary[],
});

and calling with equivalent code an add element function

function addSubsidiaryToChain(subsidiary: Subsidiary) {
  const subsidiaries = getRecoil(subsidiariesState);
  let newSubsidiaries = [...subsidiaries, subsidiary];
  console.log('new subsidiaries', JSON.stringify(newSubsidiaries));
  setRecoil(subsidiariesState, newSubsidiaries);
}

function addEmployeeToChain(employee: Employee) {
  const employees = getRecoil(employeesState);
  let newEmployees = [...employees, employee];
  console.log('new employees', JSON.stringify(newEmployees));
  setRecoil(employeesState, newEmployees);
}

The first function adds elements at the end of the array while the second will only replace elements.

recoil nexus issue

Tested in edge version 126.0.2592.102

https://stackblitz.com/edit/vite-react-ts-ervyuz?file=package.json,src%2Fdata_loader.ts

luisanton-io commented 3 months ago

Hi, I understand your confusion. I would recommend this read

To get your example working, just use an updater function instead of reading and updating the state at the same time:

function addSubsidiaryToChain(subsidiary: Subsidiary) {
  setRecoil(subsidiariesState, (subsidiaries) => [...subsidiaries, subsidiary]);
}

function addEmployeeToChain(employee: Employee) {
  setRecoil(employeesState, (employees) => [...employees, employee]);
}
luisanton-io commented 3 months ago

@javatlacati Just updated the README as well. Thanks