Reputation: 129
I have the following:
types.ts
export interface Window {
id: string;
name: string;
target?: string;
}
export interface WindowState {
windows: Window[];
}
export const ADD_TARGET = 'ADD_TARGET'
interface AddTargetAction {
type: typeof ADD_TARGET
id: string,
target: string
}
export type WindowActionTypes = AddTargetAction
actions.ts
export function AddTarget (target: string, id: string): WindowActionTypes {
return {
type: ADD_TARGET,
id: id,
target: target
}
}
REducers.ts
const initialState: WindowState = {
windows: [{
id: uuidv4(),
name: "Computer",
target: ""
}]
}
export function WindowReducer (
state = initialState,
action: WindowActionTypes
): WindowState {
switch (action.type) {
case ADD_TARGET:
return {
...state,
windows: state.windows.filter(user => user.id === action.id).map(user => ({ ...user, target: action.target }))
}
default:
return state;
}
}
where I dispatch a function providing the id of the user and then it will fetch it from the list and update it its target with the payload, but somehow when I use that function, the old state which was in my initial state and other is removed and I only have the user which I fetched its target and updated it, anybody know a way to fix it?
Upvotes: 0
Views: 47
Reputation: 837
I think the issue is you are using a filter which will return only matched user.
You should write it like this
state.windows.map(user => if(user.id === action.id) { return ({ ...user, target: action.target })) } else { return user });
Upvotes: 1