2

In my reducer i have this state:

const initialState = fromJS({
 resources: false,
 testval: [0, 0, 0, 0],})

I want to append or remove array values for testval when my action is fired. I have immutable, and immutability-helper imported but im struggling with the syntax to get this to work.

For example this isnt working - the state isnt changing:

return update(state, {
        testval: {
            $set: 'test'
        }
    });

3 Answers 3

2

It looks like you might be mixing up two different toolsets. Immutable.js is a specialized set of data structures, while the Immutability-Helper library expects to work on plain JS objects.

You might want to read through the Immutable Update Patterns section of the Redux docs, which discusses ways to properly do immutable updates on plain JS data, as well as the related links in the Prerequisite Concepts docs page.

Sign up to request clarification or add additional context in comments.

Comments

0

Ok i figured this out using Immutable.

Add to array:

return state.updateIn(['showtask'], arr => arr.push(action.userid))

Remove from array:

return state.updateIn(['showtask'], arr => arr.splice(arr.indexOf(action.userid),1))

Comments

0

its because you are updating it wrong way,

1st thing is your array will be converted to List object, so that need to be updated in list style .

in below example 1 is the index i am updating, you can use any dynamic variable for this, also item is the current value at that index. if that is object(in some other use case) you can modify the object and return it.

const initialState =  Immutable.fromJS({
 resources: false,
 testval: [0, 0, 0, 0]});

//replace initial state with state, i just posted example code

initialState = initialState.set("testval",initialState.get("testval").update(1,(item)=>{
return 2;
}));
 console.log(initialState.get("testval"))

for more detailed example you can also check this post https://onl9class.com/using-immutable-js/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.