简体   繁体   中英

How to update useState hook with Object which gets an array? with typescript

Hi I want to update new value in array located in object with useState hook.

this structure is what I want.

{ A : ['aa', 'aaa', 'aaaa', 'aaaaa'],
  B : ['bb', 'bbb', 'bbbbbbb', 'bbbbb'],
  C : ['cc', 'ccc'] }

in my code, A, B, C is category and elements in array are keyValue.

here is my code

 type selectedInterestType = { [category: string]: string[]; }; const InterestBtn = ({ category, keyValue }: Props) => { const [ selectedInterest, setSelectedInterest, ] = useState<selectedInterestType>({}); const onInterestClick = () => { setSelectedInterest({...selectedInterest, [category]: [category]? selectedInterest[category].concat(keyValue): [keyValue], }); }; return ( <button onClick={onInterestClick} > <p>{value.kr}</p> </button> ); };

I'm using react and typescript. I don't know how to update my usestate state with object, array if there are already 'category' like 'A' 'B' then add keyValue, but if it is empty, create [category]: 'keyvalue'.

from now, "Cannot read property 'concat' of undefined" error occurred

I recently using pattern like this, here is my code exemples:

setAlbums(prevAlbums => {
  // copy your previous state
  const prevAlbumsCopy = { ...prevAlbums };
  // check if your object alredy has this key 
  if (prevAlbumsCopy[category]) {
    // so with the copy you can use push bcs it's alredy a new reference
    prevAlbumsCopy[category].push(keyValue)
  } else {
    prevAlbumsCopy[category] = [keyValue]
  }

  return prevAlbumsCopy;
});

I just use Album in my exemples but you can easy refactor with your state names.

The idee of this exemple is to add a function to update your state that do everything you want, like check if element exist, set it...

I copy my object to have a different references and so trigger a rerender.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM