1

I started a little bit playing with redux and i am amazed so far. My problem right now is, that my new reducer function changes the type of one state variable and i dont want that.

The state shall have a form like that: enter image description here

I only want to delete an object from a jsons array:

pseudo:
delete state.items[item_index].jsons[json_to_delete_index]

I ended up with this reducer, which is returning the item state now as an object and not as an array.

case DELETE_JSON:
    const item_index = state.items.findIndex((url) => url.url_id === action.payload.url_id);
    const json_index = state.items[item_index].jsons.findIndex((json) => json.json_id === action.payload.json_id);
    return {
        ...state,
        items: {
            ...state.items,
            [item_index]: {
                ...state.items[item_index],
                jsons:
                    [
                        ...state.items[item_index].jsons.splice(0, json_index),
                        ...state.items[item_index].jsons.splice(json_index + 1)
                    ]
            }
        }
    };

I tried various approaches so far, but changing states inside highly nested objects seems still like a torture with redux. Does anybody maybe know a way to write it?

2 Answers 2

1

Changing state with highly nested objects can be difficult but map and filter functions are really helpful in this case

const item_index = state.items.findIndex((url) => url.url_id === action.payload.url_id);
const json_index = state.items[item_index].jsons.findIndex((json) => json.json_id === action.payload.json_id);

return { 
   ...state, 
   items: state.items.map((item, index) => (index === item_index ? 
   { ...item, item.jsons.filter((json, i) => (i !== json_index)) } : item)) 
   };
Sign up to request clarification or add additional context in comments.

Comments

0

I solved it by using update() from immutability-helpers. Very handy

import update from 'immutability-helper';

/* some other code */

case DELETE_JSON:
    const item_index = state.items.findIndex((url) => url.url_id === action.payload.url_id);
    const json_index = state.items[item_index].jsons.findIndex((json) => json.json_id === action.payload.json_id);
    return update(state, {
            items: {
                [item_index]: {
                    jsons: {$splice: [[json_index]]}
                }
            }
        });

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.