0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【React】配列stateにpushした時に出るエラー

Last updated at Posted at 2022-02-03

エラー内容

Uncaught TypeError: Cannot add property 0, object is not extensible
    at Array.push (<anonymous>)

配列stateに対してpush(破壊的メソッド)した時にコンソールに出力されます。

const cardsState = atom<string[]>({
  key: AtomKeys.CARDS_STATE,
  default: []
});
const [cards, setCards] = useRecoilState(cardsState);
cards.push['aaa.png']; ← ここでエラー
setCards(cards);

配列stateはミュータブルで破壊的なメソッド(push、spliceなど)を持っています。
しかし、stateを破壊的メソッドで変更すると、元のstateの変更が検知されず再描画されなくなってしまうためエラーになります。
破壊的なメソッドについてや具体的な理由は参考にさせていただいた参考文献をご覧ください。

修正内容

const cardsState = atom<string[]>({
  key: AtomKeys.CARDS_STATE,
  default: []
});
const [cards, setCards] = useRecoilState(cardsState);
setPlayersCards([...cards, 'aaa.png']);

スプレッド演算子で新しい配列としてsetする。
(配列を別配列にコピーしてpushするのもOK)

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?