user2220139
user2220139

Reputation: 35

Redux reducer adds to array instead of overwriting it

I have a redux store set up with 1 array object. I have written a reducer to update the store by replacing the existing array with the new one. For some reason the reducer seems to add to the existing array instead of replacing it. Any ideas why this is occuring?

const initState = {
    articles: [
        {key: 1, title: "ggg", content: "sfsdfdsf"},
        {key: 2, title: "gdffgg", content: "rgkrdpo"},
        {key: 3, title: "gfsgg", content: "s;flksd;fl"}
    ]
}

const rootReducer = (state = initState, action) => {
    if(action.type === "UPDATE_ARTICLES"){
        var newArticles = action.newArticles;
        return{
            articles: newArticles
        };
    }else{
        return state
    }
}


export default rootReducer

Upvotes: 0

Views: 430

Answers (1)

tachko
tachko

Reputation: 161

you need to return the state in your reducer every time.

return {    ...state,
            articles: newArticles
        };

Upvotes: 1

Related Questions