Reputation: 13
development enviroment
・ react
・ typescript
state groups are arrays.
I want to add a group to the array of groups when the onClickGroups function is called.
How to implement
interface ISearch {
name: string;
age: number;
groups?: IGroups[];
interface IState {
searchState: ISearch;
text: string,
display: boolean
}
const Index: FC = () => {
const [state, setState] = useState<IState>({
searchState: initialSearch,
text: '',
display: boolean
});
const onClickGroups = (group: IGroups) => {
setState({ ...state, searchState: { ...state.searchState, groups: group } });
};
Upvotes: 0
Views: 108
Reputation: 493
You can use spread JavaScript ES6 (and TypeScript) operation with the current groups and add the new group element in the array:
const onClickGroups = (group: IGroups) => {
const currentGroups = state.searchState.groups;
setState({
...state,
searchState: {
...state.searchState,
groups: [ ...currentGroups, group ]
}
});
};
Upvotes: 4