James111
James111

Reputation: 15903

Immutable setIn nested object returning invalid keyPath error

I've got the following object:

const initialState = Map({
  posts: {
    most_popular: [],
    trending: [],
    latest: [],
  }
});

And I'm trying to update a sub object within entries. Here is what I've tried:

intialState.setIn(["posts", "most_popular"], ["array", "of", "values"]);

Running this set command will return

Uncaught Error: Invalid keyPath()

Am I missing something? I don't need to create sub maps do I? E.g

const initialState = Map({
      posts: Map({
        most_popular: [],

Obviously that doesn't work (I've tried), but maybe there is another way of setting sub object up?

EDIT:

Getting the object, and updating like so works:

state.get("entries").most_popular = ["k"];

But this means my entries.most_popular (trending, latest) aren't immutable? Is there a way to make sub objects immutable?

Upvotes: 1

Views: 1015

Answers (1)

VanDanic
VanDanic

Reputation: 432

Instead of using Map(), use fromJS(). If you use Map(), then the array under your key most_popular is a standard JS object, not an Immutable.js structure.

Thus:

const initialState = fromJS({
  posts: {
    most_popular: [],
    trending: [],
    latest: [],
  }
});

Now everything is an Immutable object. Then you can easily do:

initialState.setIn(["posts", "most_popular"], ["array", "of", "values"]);

Upvotes: 2

Related Questions