Skip to content

Calling toJS on the result of an Immutable map causes the Immutable map to be converted to a JS object when being passed as a prop to a React component inside of the map function #2029

Open
@ender2012

Description

@ender2012

What happened

I am looking into upgrading from Immutable 3 to Immutable 4.3.7 and I ran into a strange difference that I am having trouble explaining.

When mapping over a list of Immutable maps and then using toJS to create a an array that can be rendered by React, Immutable.Maps that are passed as a prop to a component inside the map function get converted to a javascript object in Immutable 4.

I found that if I used toArray instead of toJS this does not happen so this seems to be a fine workaround but I am wondering if this is expected with toJS and what may have changed between 3 and 4 that may have caused this behaviour to be different.

How to reproduce

Since this is a somewhat complex situation I think its easier to show with code.

This first example creates an Immutable List of Immutable Map that contain a single key called name. Inside our JSX we map over the Immutable List and pass the itemData to a component called item which renders a div with the text name that it tries to pull out by calling itemData.get('name'). Notice that this codesanbox errors out saying:

itemData.get is not a function

Codesanbox using toJS

This is occurring because itemData has been converted to a javascript object inside of the map function (instead of only converting the whole result of the map afterwards which is how it worked in Immutable 3).

In this second example I use toArray instead of toJS and it all works as expected:

Codesanbox using toArray

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions