N
N
Nikita2019-08-20 15:50:46
redux
Nikita, 2019-08-20 15:50:46

Why is it not being added to the array?

Tell me, please, why is not adding to the array?
The processing of the state happens in the reducer:

export function AddTodoReducer(state = initialState, action) {
  switch (action.type) {

    case ADD_TODO:
      let newTodo = {
        id: action.id,
        text: action.text,
        completed: false
      }
      let newState = {...state}
<b>      newState.todos = [...state.todos]</b> // Проблема в этой строке
      newState.todos.push(newTodo)
      return newState

    default:
      return state
  }
}

The problem is in this line newState.todos = [...state.todos] when I remove it, the addition occurs, but it's wrong, according to the rule of immutability.
Additional files:
AddTodo.js calls addTodoAction (input.value)
import React from 'react'
/* import Input from '../../UI/Input/Input' */
import Button from '../../UI/Button/Button'
import classes from './AddTodo.module.css'

const AddTodo = ({ addTodoAction }) => {

  let input
    const submitHandler = event => {
    event.preventDefault()
    if (!input.value.trim()) {
      return false
    }
    addTodoAction(input.value)
    input.value = ''
  }

  return (
    <form onSubmit={submitHandler} className={classes.AddTodo}>
      <input ref={node => { input = node }} />
      <Button>Добавить</Button>
    </form>
  )
}

export default AddTodo

Which is taken from TodoListContainer.js
import { connect } from 'react-redux'
import AddTodo from '../components/AddTodo/AddTodo'
import {addTodo} from '../store/actions/index'

const mapStateToProps = state => {
  return {
    
  }
}

const mapDispatchToProps = dispatch => {
  return {
    addTodoAction: text => dispatch(addTodo(text))
  }
}
export default connect(mapStateToProps, mapDispatchToProps)(AddTodo)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-08-21
@rockon404

Cannot be added.
Demo .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question