TO YUU
TO YUU

Reputation: 13

react change the contents of state

I want to change the query part of name, age, country of data of state.
... {data: {... state.data, [key] .query: e.target.value}}, but at [key] .query, Parsing error:':' expected.eslint It will end up. How should I fix it? If anyone knows, please let me know.

interface Data {
  name?: Name;
  age?: Age;
  country?: Country;
}

interface Name {
  query: string;
  current: boolean;
}

interface Age {
  query: string;
  current: boolean;
}

interface Country {
  query: string;
  current: boolean;
}

const initial: Name | Age | Country = {
  query: '',
  current: false,
};

const initialdata: Data = {
  name: initial,
  age: initial,
  country: initial,
}

interface State {
  data: Data;
  text: string;
  modal: boolean
}

const Index: FC = () => {
  const [state, setState] = useState<State>({
    data: initialdata,
    text: '',
    modal: false,
  });


  // Where to call this function, one of Data's name, age, country is passed like onChangeWithKey (ChangeEvent <HTMLInputElement>,'name').
  const onChangeWithKey = (e: any, key: string) => {
    setState({ ...state, ...{data: { ...state.data, [key].query: e.target.value } } });
  };

Upvotes: 0

Views: 48

Answers (1)

Drew Reese
Drew Reese

Reputation: 202618

[key].query isn't a valid object key. Also, make sure you maintain the state.data property.

const onChangeWithKey = (e: any, key: string) => {
  setState({
    ...state, // <-- copy state
    data: {
      ...state.data, // <-- copy state.data
      [key]: { // <-- update specific key property
        ...state.data[key], // <-- copy state.data[key]
        query: e.target.value // <-- update query property
      },
    } ,
  });
};

Upvotes: 1

Related Questions