Reputation: 522
I ma having a simple reducers state that was working fine. M reducer is below.
const initialState =
{
plan: [
{
id: 0,
text: 'Submit math assignment at noon.',
completed: false
}
]
}
function mytodo(state = initialState, type) {
switch(type) {
...
default:
return state;
}
}
My app works fine. Then concat some localstorage data to my state. My state now returns undefined.
const storageItems = JSON.parse(localStorage.getItem('plan'));
function mytodo(state = initialState, type) {
switch(type) {
...
default:
console.log('the storage data is', storageItems);
return storageItems ? state.plan.concat(storageItems) : state;
}
}
I confirmed the storage items above has data yet my reducer returned undefined as plan to my component. I then changed this to.
const storageItems = JSON.parse(localStorage.getItem('plan'));
if(storageItems) {
initialState = initialState.todos.concat(storageItems);
console.log('the states are', initialState);
}
function mytodo(state = initialState, type) {
switch(type) {
...
default:
return state;
}
}
and change initialState to let. Still it returns undefined. Initial state from the console above returns the complete result i needed. However, it does not return the value to my component provided i update the initialState. Please what am i doing wrong? How do i addressed this? Any help would be appreciated.
Upvotes: 1
Views: 533
Reputation: 4948
Array.prototype.concat()
returns a new array object https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat . Check where the error is thrown. The object may not be empty but the order might have been changed.
const initialState =
{
plan: [
{
id: 0,
text: 'Submit math assignment at noon.',
completed: false
}
]
}
From the above, initialState.plan should return your plan array.
However,
initialState = initialState.todos.concat(storageItems);
Would return new array. Now your initialState would take the form
initialState = [{
id: 0,
text: 'Submit math assignment at noon.',
completed: false
}]
Therefore if you have your state.plan
anywhere would throw an undefined error because your state have changed. Hope here about concat https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/concat
Upvotes: 1