reactdontact
reactdontact

Reputation: 53

The state of this element is Undefined for first time?

I am trying to create toggle switch in my application and i am new to redux. Posting this question after trying very hard and looking eveywhere online.Please help. My Reducer is below:

const initialState = {
    preview: "off",
    cards:
};

const cardReducer = (state = initialState, action) => {
        switch (action.type) {

            case "FIND_ALL_CARDS":
                return {
                    cards: action.cards
                };
            case "DELETE_CARD":
                return {
                    cards: state.cards.filter(card => card.id !== action.cardId)
                };
            case "CREATE_CARD":
                return {
                    cards: [...state.cards, action.card]
                };
            case "PREVIEW":
                console.log(state); // I get cards[] in the state but no preview.
                let swtch = "on";
                if (state.preview === "on") {
                    swtch = "off";
                }
                console.log(state.preview); // Undefined 

                return {
                    cards: state.cards,
                        preview: swtch
                };
            default:
                return state;
        }

I have connected properly in my component

const stateToPropertyMapper = state => ({
  cards: state.cards.cards,
  preview: state.cards.preview
});

I get undefined for the first time i toggle the switch but after first toggle i get the state. Please help me on this enter image description here

Upvotes: 1

Views: 473

Answers (1)

Andon Mitev
Andon Mitev

Reputation: 1504

Basically from reducer you are returning a COPY of your state, and when you return {cards: []}, you are losing all of the rest props from the state. When you are mutating state in FIND_ALL, DELETE and Create CARD you need to return rest part of the state as well. Edit like this

case "FIND_ALL_CARDS":
    return {
        ...state
        cards: action.cards
     };

Do it in all actions, dont forget to pass previous prop of state when u mutate single one

Upvotes: 2

Related Questions