0

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 } });
  };
TO YUU
  • 13
  • 6
  • See [What is the best way to add a value to an array in state](https://stackoverflow.com/questions/26505064/what-is-the-best-way-to-add-a-value-to-an-array-in-state) – Shivam Jha Oct 13 '20 at 18:58

1 Answers1

4

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 ]
    }
  });
};
mortezashojaei
  • 422
  • 2
  • 11
LBald
  • 473
  • 2
  • 11