Can't convert undefined or null to reducex object
I am using Redux to create a simple store and unfortunately this is a bug:
Cannot convert undefined or null to object
Browser points to Redux import line
import * as redux from "redux"
I also tried importing it this way but it gave the same error import {createStore} from "redux"
this 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 your fav Color",
votes: 230
}
})
+3
source to share
1 answer
This error occurs like in your reducer, you are trying to propagate a non-existent property to a state object
...state.polls,
To do this, you need to define the shape of your initial state as
const initialState = {
polls: [],
};
Complete working code of your example
import * as redux from "redux"
const initialState = {
polls: [],
};
let reducer = (state = initialState, 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 your fav Color",
votes: 230
}
})
+5
source to share