React.js
How to manage state with useState hook
seoca
2022. 3. 3. 10:18
1. simple way using destructuring
const AdminProductDetail = () => {
const params = useParams();
const navigate = useNavigate();
const [product, setProduct] = useState({
name: '',
price: 0,
image: '',
brand: '',
category: '',
countInStock: 0,
description: '',
});
const getData = async (id) => {
try {
const { data } = await axios.get(`/api/products/${id}`);
const { name, price, image, brand, category, countInStock, description } = data;
setProduct({
name,
price,
image,
brand,
category,
countInStock,
description,
});
} catch (error) {
console.log(error);
}
};
2. could be better when not many states are needed
const AdminProductDetail = () => {
const params = useParams();
const navigate = useNavigate();
const [name, setName] = useState('');
const [price, setPrice] = useState(0);
const [image, setImage] = useState('');
const [brand, setBrand] = useState('');
const [category, setCategory] = useState('');
const [countInStock, setCountInStock] = useState(0);
const [description, setDescription] = useState('');
const getData = async (id) => {
try {
const { data } = await axios.get(`/api/products/${id}`);
console.log('getsingledata', data);
setName(name);
setPrice(price)
setImage(image)
setBrand(brand)
setCategory(category)
setCountInStock(countInStock)
setDescription(description)
} catch (error) {
console.log(error);
}
};