1
votes

after action "ADD_CONTACT", the new state gets updated in redux, but inital state doesn't reatin even though i used the spread operator to add the initial state.

this is my reducer:

const initalstate = {
  information :   [
        {
            key: 1,
            name: "firstname"
        }
    ]
}
export const productReducer = (state = initalstate, action)=>{
  
    switch (action.type) {
        case "ADD_CONTACT": 
        state = {...state , information :  action.payload,}
        console.log("state :", state)
        default:
           return state;
    }
}

and here is my dispatch function:

const updatedata = [
    { id : "2", name : "secondname" },
    { id : "3", name : "thirdname"}
]

export const Footer = () => {
    const data = updatedata;
    const currentState = useSelector(state => state)
    const dispatch = useDispatch()
    const handSubmit = (data)=>{
    dispatch(
            { type : "ADD_CONTACT",
                payload :data } )
        console.log(currentState)}
    return (
        <div className="btn">
            <button onClick={()=>{handSubmit(data)}}>add</button>
        </div>
    )
}

id 2 & 3 get added but initialstate which contains id 1, gets removed from state. Please let me where I am going wrong. Thanks in advance,

1

1 Answers

1
votes

You're not using the current state values for the reduced state:

export const productReducer = (state = initalstate, action)=>{
    switch (action.type) {
        case "ADD_CONTACT": 
          state = {
            ...state,
            information :  [...state.information, ...action.payload] // Combine them
          }
        default:
           return state;
    }
}