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

12.9k views Asked by At

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
    };
}
4

There are 4 answers

2
J.Doe On BEST ANSWER

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;
  }
}
0
adamTrz On

I think that somehow, into your first loop you added string into state.data... Try something like this: list = state.data.concat(action.toDoData)
Or with ES6 spread:
list = [...state.data, action.toDodata]

0
chrisfisher On

You want the array spread operator, i.e.

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

is your action.toDoData an array? If yes, then it should be

state.data.concat(action.toDoData)