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 } });
  };
1

1 Answer 1

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 ]
    }
  });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.