2

Hello I am working on a announcements app, and i need to update or edit one of announcements. I am stuck at this point and don't know how to solve it.

const announcements = createSlice({
    name: 'announcements',
    initialState: {
        announcements: [
            {id: 1, title: 'dog', description: 'dog eat apple', dateAdded: '21.10.1120'},
            {id: 2, title: 'cat', description: 'cat eat meat', dateAdded: '11.1.2020'},
            {id: 3, title: 'monkey', description: 'monkey eat banana', dateAdded: '11.5.2021'},
        ],
    },
    reducers: {
        addAnnouncement: (state, action) => {
            state.announcements = [...state.announcements, action.payload];
        },
        deleteAnnouncement: (state, action) => {
            state.announcements = state.announcements.filter(announcement => announcement.id !== action.payload.id);
        },
        editAnnouncement: (state, action) => {
            const {description, title, id, dateAdded} = action.payload;
            state.announcements = state.announcements.find(announcement => announcement.id === id

        }
    }
})
````

Oleg Salo
  • 23
  • 3

1 Answers1

0

It would be easier and more efficient if your structure your data differently

const announcements = createSlice({
        name: 'announcements',
        initialState: {
            announcementsById: {
                1: {id: 1, title: 'dog', description: 'dog eat apple', dateAdded: '21.10.1120'},
                2: {id: 2, title: 'cat', description: 'cat eat meat', dateAdded: '11.1.2020'},
                3: {id: 3, title: 'monkey', description: 'monkey eat banana', dateAdded: '11.5.2021'},
            },
        },
        reducers: {

            editAnnouncement: (state, action) => {
               state.announcementsById[action.payload.id] = action.payload
    
            }
        }
    })

Take a look at this doc: https://redux.js.org/usage/structuring-reducers/normalizing-state-shape

Youssef Bouhjira
  • 1,599
  • 2
  • 22
  • 38