reduxで配列操作する時のメモ


目的

reduxで配列操作する時にサラッと確認したいメモです。
Reducerのみ

cardReducer.js
import {
    ADD_CARD,
    UPDATE_CARD,
    DELETE_CARD,
} from './cardTypes'

const initialState = {
    imageList: []
}

const cardReducer = (state = initialState, action) => {
    switch (action.type) {
        // 要素の追加
        case ADD_CARD:
            return {
                ...state,
                imageList: [...state.imageList, action.payload]
            }
        // 要素の更新
        // 要素のIDで更新対象を確定
        case UPDATE_CARD:
            return {
                ...state,
                imageList: state.imageList.map(el => el.id === action.payload.id ? action.payload : el)
            }
        // 要素の削除
        // 要素のIDで削除対象を確定
        case DELETE_CARD:
            return {
                ...state,
                imageList: state.imageList.filter((item) => item.id !== action.payload)
            }
        default: return state
    }
}

export default cardReducer