1

import dateDiff from 'date-diff';
import moment from 'moment';


const calcDate = (date) => {
    let newDate = moment(new Date(date)).fromNow();
    console.log(newDate)
   return newDate;
};//end of calcDate

const removeByIndex = (state=[], index) => {
};



const addToListReducer = (state=[], action) => {
    let reminders;

    
    switch (action.type) {
        case 'ADD_TO_LIST':
            reminders = [...state, {task: action.task, dueDate:calcDate(action.dueDate)}]
            console.log('this is the reminders in the reducer', reminders);
            return reminders;
        case "REMOVE_FROM_LIST":
            console.log("Removing from the list", action.index)
            reminders = removeByIndex(state, action.index)
            return reminders;
        default:
            return state;

    } //end of switch statement
}

export default addToListReducer;

On the removeByIndex function, I am passing the state(the full array of task) and the index number of that array. How would i delete the element of that array by using the index. I feel since it is react, that i need to use a filter in it?

2
  • arr.filter((elem, index) => return index !== action.index); Commented Sep 5, 2017 at 23:05
  • arr.slice(0, action.index).concat(arr.slice(action.index+1)) would also work Commented Sep 5, 2017 at 23:07

1 Answer 1

3

You're right, since you are using Redux, the state needs to be immutable. So you can't edit the array directly and return the same instance of it, but instead you've to create a new one.

In the redux documentation, it explains few ways of how to do it.

So you could do:

function removeItem(array, index) {
    return [
        ...array.slice(0, index), // first part of the array, 0 to index (excluded)
        ...array.slice(index + 1) // the rest, after the index
    ];
}

Or simply (but may be less performant):

function removeItem(array, index) {
    return array.filter((_, i) => i !== index); // all items except at index
}
Sign up to request clarification or add additional context in comments.

3 Comments

In this case, I would not recommend using "filter" to remove by index. Concatenating the slices should be readable enough and is significantly more efficient.
filter may be more readable and shorter (especially if removeItem is converted to a lambda), but you're right that if performance is a concern then the first should be used. I've updated my answer to make it clearer.
I guess readability is in the eyes of the beholder ;) You've earned my +1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.