rtfeldman / seamless-immutable

Immutable data structures for JavaScript which are backwards-compatible with normal JS Arrays and Objects.
BSD 3-Clause "New" or "Revised" License
5.37k stars 195 forks source link

How to apply splice with seamless-immutable? #251

Open etairi opened 6 years ago

etairi commented 6 years ago

I'm using seamless-immutable inside React app, and I have a code segment like this in my saga:

let parsedData = yield select(state => state.post.posts);
parsedData = postUtils.deleteLike(parsedData, payload);

And my deleteLike method looks like this:

const deleteLike = (parsedPosts, likeId) => {
    let posts = Immutable.asMutable(parsedPosts);

    Object.entries(posts).forEach(
        ([_, userPosts]) => {
            Object.entries(userPosts).forEach(
                ([_, post]) => {
                    const found = post.likes.filter(l => l.id === likeId);
                    if (found.length > 0) {
                        const index = post.likes.indexOf(found[0]);
                        post.likes.splice(index, 1);
                    }
                }
            );
        }
    );

    return posts;
};

So, basically I want to remove one element from one of the inner arrays that is found inside the object. Though, the above code throws an error saying that splice cannot be invoked on an Immutable data structure. I though the call to asMutable() is going to convert it to a mutable object and store in posts variable. So basically asMutable() doesn't make the nested object mutable all the way? Because I also need at later stage to push into post.likes, not just remove an element as above. So, I want to make the whole object mutable so that I can work comfortably.

crudh commented 6 years ago

@etairi Immutable.asMutable(obj, {deep: true}) should do the trick.