Sara
Sara

Reputation: 13

I cannot access state object in my React Redux application

I'm new to React and Redux and I'm building a simple SPA where I'm adding projects to a list via input form. I initialized the state, I have 2 default project values and I'm successfully adding projects, but when I want to remove an object in the reducer I cannot access state.projects it says that is undefined and I cannot understand why. Can you help me please?

This is my reducer:

const projects = (state = 'ADD_PROJECT', action) => {
    switch (action.type) {
        case 'ADD_PROJECT':
            return [
            ...state,
            action.payload
        ]
        case 'REMOVE_PROJECT':
            console.log(state.projects);
            return Object.assign({}, state, {
                projects: [state.projects.filter(project => project.id !== action.payload.id)],
             })
        default:
            return state
} 
export default projects

This are the actions

export const addProject = (project) => {
    return {
        type: 'ADD_PROJECT',
        payload: project
    }
}

export const removeProject = (id) => {
    return {
        type: 'REMOVE_PROJECT',
        payload: id
    }
}

This is how I create the store and the initial state

const initialState = { 
    projects: [{
        id:100, 
        name:"Project 1"
    },{
        id:101,
        name:"Project 2"
    }] 
};

let store = createStore(projectApp, initialState, 
window.__REDUX_DEVTOOLS_EXTENSION__ && 
window.__REDUX_DEVTOOLS_EXTENSION__());

render(
    <Provider store={store}>
         <App />
    </Provider>,
    document.getElementById('root')
)

Upvotes: 0

Views: 785

Answers (3)

miles_christian
miles_christian

Reputation: 111

Your initial state is an OBJECT with a projects ARRAY, but when you ADD_PROJECT you return an ARRAY of your state plus the new project. You must return the same format:

 case 'ADD_PROJECT':
            return {
            ...state,
            projects: [
               ...state.projects,
               action.payload
            ]                
        } 

Upvotes: 0

Fawaz
Fawaz

Reputation: 3560

It seems there's an extra bracket when filtering out projects. Also the payload is id itself (id === action.payload). Try this in REMOVE_PROJECT reducer :

projects: state.projects.filter(project => project.id !== action.payload)

Upvotes: 1

cdimitroulas
cdimitroulas

Reputation: 2549

It's a little bit difficult to know what's going on without seeing what your store state is after you have added your projects.

However, it seems as though you are not adding the projects to the correct part of the state. Try changing the code for the ADD_PROJECT case to this:

case 'ADD_PROJECT':
  return [
    ...state.projects,
    action.payload
  ]

Upvotes: 0

Related Questions