2023.03.02
0. Background
The reason that made me search for and use it is basically that I wanted to manage a state of an array through useState hook. It didn't work when I tried just updating the array with array functions like this:
import {useState} from 'react';
const [tags, setTags] = useState([]);
const setTags = (tag) => {
setTags(tags.push(tag));
};
const removeTags = () => {
setTags(tags.pop(tag));
};
So, it was needed to fix and make it run in an intended way and I found out spread syntax.
1. Reason the previous code didn't work
According to official React docs, arrays are basically an object. Therefore, we should treat arrays in React state as read-only. We can't use arr[0] = 'bird', which is the re-assigning, and also we need to avoid using push() or pop() which are the methods that mutate the array. Instead, we can use other ways that React Docs suggests.
tags[0] = "cool";
setTags(tags.pop());
setTags(tags.push());
2. Alternatives
Use these methods:
/* When you wanna add an element */
setTags([...arr,element]);
/* When you wanna remove an element */
setTags(tags.filter(tag => if tag === element));
/* When you wanna replace an element */
setTags(tags.map(tag => ));
'Project > Rate My Resident' 카테고리의 다른 글
5. Query Callback (쿼리콜백) in Node.js (0) | 2023.04.11 |
---|---|
4. Using Variables in useEffect (useEffect에서 변수 쓰기) (0) | 2023.03.16 |
2. Connect Node.js to React.js with Express and Mysql (0) | 2023.01.02 |
1. How to put props to a page with enter key (엔터키 눌렀을 때 페이지로 인자 넘겨주기) (0) | 2022.12.31 |
0. Motivation / Folder Structure (0) | 2022.12.24 |