Concat actually concatenates instead of adds to array. React Native Javascript

tlagreca picture tlagreca · Dec 18, 2016 · Viewed 10.1k times · Source

Im new to react Native and Javascript programming in general and Im trying to create a simple 'To Do' app with in React Native and redux.

Im attempting to add a 'To Do' to the the array in my reducer as seen below.

import * as types from '../actions/actionTypes'

const initialState = {
    data: []
};

export default function toDo(state = initialState, action) {

    let list
    console.log(action + " action")
    switch (action.type) {
        case types.ADD:
        list = state.data.concat([action.toDoData])
            return {
                ...state,
                data: list || []
            }
        default:
             return state;
    }
}

The result shows AddToDo Results you can see 'First Thing' and 'Second Thing' are my two added results and they concat onto the same row.

My first thought was that there was something wrong with my dumb or presentational ListView which takes it data as below.

<MyList data={this.props.data}/>

So i tried this...

<MyList data={['firstThing', 'secondThing', 'thirdThing']}/>

and it works!!! This is the reason I'm thinking the error is in the reducer.

Please let me know what other code would be useful. Any insights would be MUCH appreciated.

This is the action.

import * as types from './actionTypes.js';

export function addToList(toDoData) {
    return {
        type: types.ADD,
        toDoData: toDoData
    };
}

Answer

J.Doe picture J.Doe · Dec 18, 2016

Here's some insights on how you actually 'push' data into an array

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");

//fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi"];

Or you can just

export default function toDo(state = initialState, action) {
  switch (action.type) {
    case types.ADD:
      return {
        data: [...state.data, action.toDoData]
      }
    default:
      return state;
  }
}