javascriptlistimmutable.jsimmutablelist

Appending new Immutable Map value to Immutable List


I have below a piece of code wherein I need to push a new Immutable Map value to an Immutable List on each forEach iteration. The flow goes into if condition as expected, but nothing is being pushed to the listOfFiles List. The console at the end of the forEach print list as List[0].

Any hint, on what should be corrected over here so it works fine?

Code

const formatListOfFilesObjectForAPI = (selectedListOfFileIds, allFilesData) => {

  const listOfFiles = new Immutable.List();
  selectedListOfFileIds.forEach(fileId => {
    const fileObject = allFilesData.getIn([fileId, 'result']);
    if(fileObject && fileObject.size > 0) {
      if(fileObject.get('provider') === 'intranet') {
        listOfFiles.push(new Immutable.Map({
          file_id: fileObject.get('fileId'),
          provider: fileObject.get('provider')
        }));
      } else {
        listOfFiles.push(new Immutable.Map({
          file_id: fileObject.get('fileId'),
          provider: fileObject.get('provider'),
          name: fileObject.get('basename'),
          type: fileObject.get('extension'),
          size: fileObject.get('size'),
          version: fileObject.get('version'),
        }));
      }
    } else {
      listOfFiles.push(new Immutable.Map({
        file_id: fileId,
        provider: 'intranet'
      }));
    }
  });

  console.log('listOfFiles', listOfFiles);

  return listOfFiles;
};

Solution

  • You're trying to mutate an immutable list, so it's normal it doesn't change.

    If you check the Immutable documentation for e.g. push(), you'll see that it returns a new list with the result. Therefore in your example, you need to replace every listOfFiles.push with listOfFiles = listOfFiles.push.

    Alternatively, use a regular array you can simply push() to and convert it to an immutable list at the end.