Jack23
Jack23

Reputation: 1396

React-Redux: Clean the state

In my app I do two related gets. From the first get I get all the ids, when one of these ids is chosen, it is used to make a new api call that gives me back some data.

So after the first get I have a situation like:

docent:  (2) [{…}, {…}]
          0: {id: "12", name: "Name1", surname: "Surname1"}
          1: {id: "13", name: "Name2", surname: "Surname2"}
          length: 2__proto__: Array(0)

agenda:  []

after the user chooses one of the ids, the agenda array is also populated with the information retrieved according to that id like:

agenda:   (2) [{…}, {…}]
          0: {id: "1", docent_id: "12", date: "2020-05-27", start_at: "09:00:00", end_at: "10:00:00"}
          1: {id: "2", docent_id: "12", date: "2020-05-27", start_at: "10:00:00", end_at: "11:00:00"}
          length: 2

My problem is that: If the user changes the id of the docent array again, the agenda array becomes:

agenda:  (3) [{…}, {…}, {…}]
         0: {id: "1", docent_id: "12", date: "2020-05-27", start_at: "09:00:00", end_at: "10:00:00"}
         1: {id: "2", docent_id: "12", date: "2020-05-27", start_at: "10:00:00", end_at: "11:00:00"}
         2: {id: "3", docent_id: "13", date: "2020-05-28", start_at: "09:00:00", end_at: "10:00:00"}
         length: 3

So I have the past informations plus the new information.

I would like to be able to delete the information saved in the agenda in case the user changes the docent's ID. How can I do?

Actions:

export const agendaList = (id, agenda) => {
    return (dispatch) => {
        fetch(api + id, {
            headers: {
                Accept: "application/json",
            },
        })
            .then((result) => result.json())
            .then((agenda) => {
                dispatch({
                    type: "AGENDA_LIST",
                    agenda: agenda
                });
            })
            .catch((error) => console.log("An error occurred.", error));
    };

Reducers:

const initialState = {
agenda: []
}
export const reducer = (state = initialState , action) => {
case 'AGENDA_LIST':
            return {...state, agenda: [...state.agenda, ...action.agenda]};
        default: 
            return state;
    }

Upvotes: 0

Views: 34

Answers (1)

moonwave99
moonwave99

Reputation: 22817

Your reducer is merging the current state and the action data:

return {...state, agenda: [...state.agenda, ...action.agenda]};

You want to replace the current state agenda:

return {
  ...state,
  agenda: action.agenda
};

Upvotes: 1

Related Questions