Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert undefined or null to object redux

I'm using Redux to make a simple store and unfortunately it's throwing this error:

 Cannot convert undefined or null to object

The browser points to the line of importing Redux

import * as redux from "redux"

I've also tried to import it this way but it gave the same error import { createStore } from "redux"

this the code :

import * as redux from "redux"

let reducer = (state ={}, action) =>{
    switch(action.type) {
        case "ADD_POLL":
            return {
                polls: [
                    ...state.polls,
                    action.poll
                ]
            }
        default:
            return state
    }
}

let store = redux.createStore(reducer)

store.subscribe(()=>{
    let currentState = store.getState()
    console.log(currentState)
})

store.dispatch({
    type: "ADD_POLL",
    poll: {
        id: 1,
        title: "What's  your fav Color",
        votes: 230
    }
})
like image 324
BaHaa Jr. Avatar asked May 29 '17 22:05

BaHaa Jr.


2 Answers

That error is thrown as in your reducer you are trying to spread a non existent property on the state object

...state.polls,

To be able to do so you have to define the shape of your initial state as

const initialState = {
    polls: [],
};

Full working code of your example

import * as redux from "redux"

const initialState = {
    polls: [],
};

const reducer = (state = initialState, action) =>{
    switch(action.type) {
        case "ADD_POLL":
            return {
                polls: [
                    ...state.polls,
                    action.poll
                ]
            }
        default:
            return state
    }
}

const store = redux.createStore(reducer)

store.subscribe(()=>{
    let currentState = store.getState()
    console.log(currentState)
})

store.dispatch({
    type: "ADD_POLL",
    poll: {
        id: 1,
        title: "What's  your fav Color",
        votes: 230
    }
})
like image 61
Stefan J Avatar answered Nov 02 '22 12:11

Stefan J


createStore API is updated. createStore() now receives an enhancer such as applyMiddleware() as the last optional argument.

Example:

 const store = createStore(
  rootReducer,
  initialState,
 applyMiddleware(thunk, logger)
)

Here's the link for details https://github.com/reduxjs/redux/releases/tag/v3.1.0

like image 1
Burhan Atique Avatar answered Nov 02 '22 12:11

Burhan Atique