Reputation: 47
I have store like this
export const list = [
{
id: 0,
tableName: 'example',
tasks: [
{
task_id: 0,
task_short: 'lorem',
task_full: 'lorem ipsum lorem ipsum lorem ipsum',
time_created: '10:20',
time_created: null,
},
{
task_id: 1,
task_short: 'andsf',
task_full: 'lorem ipsum tes tes est',
time_created: '13:20',
time_created: null,
}
]
}
]
if I change tableName or adding new one using this reducer
import { list } from './list'
export default (state = list, action) => {
const { type, payload } = action
switch(type) {
case 'ADD_TABLE':
return [...state, payload]
case 'DELL_TABLE':
return state.filter( ( tabl ) => tabl.id != payload )
case 'CHANGE_TITLE':
let basket = state.map( bas => bas.id == payload.id ? bas.tableName = payload.val : bas )
return [...state]
case 'ADD_TASK':
const newer = state.map( tas => tas.id == payload.id ? tas.tasks.push(payload.t) : tas)
return [...state]
default:
return state
}
}
all works!!
but if I pushing new task in tasks , in console it stored, but not renders.
For making it render, I have to change tableName , and after it all is appears
I suppose the problem in here
case 'ADD_TASK':
const newer = state.map( tas => tas.id == payload.id ? tas.tasks.push(payload.t) : tas)
return [...state]
here is demo http://kanban.antus.pro/
and repo enter link description here
Upvotes: 2
Views: 55
Reputation: 350
Array.push()
changes initial array, that's anti-pattern in redux https://redux.js.org/faq/immutabledata
You should change this row
const newer = state.map( tas => tas.id == payload.id ? tas.tasks.push(payload.t) : tas)
on this one
const newer = state.map( tas => tas.id == payload.id ? [...tas.tasks, payload.t] : tas)
so you will not mutate initial tas.tasks
array
try not to use methods from this list in reducer https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Mutator_methods
Upvotes: 1