김일혁
김일혁

Reputation: 429

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

Upvotes: 0

Views: 964

Answers (1)

Melvynx
Melvynx

Reputation: 1175

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.

Upvotes: 1

Related Questions