Answer the question
In order to leave comments, you need to log in
Manipulations with state and some questions about rendering and architecture in React?
Hello! I didn’t want to ask for help for a long time, I was looking for it myself, but due to the lack of the necessary knowledge I had to give up
and
write
here loading data from the API, we load this data into state = { result: [] }, then we render this data by pulling data from state and passing it through the component (which styles the data). As a result, we have 25 styled components with data on the page, and I want that when the button on this component is clicked, it will be added to the basket state = { basket: [] } .
This is how it looks
const NewsItem = ({ styles, id, name, tagline, abv, image, clickFilter } ) => (
<div>
<ul className={styles}>
<li> <img src={image} alt="empty"
height='150'></img> </li>
<li> {`ID - ${id}`} </li>
<li> {`Название - ${name}`} </li>
<li> {`Тэг - ${tagline}`} </li>
<li> {`Крепость - ${abv}`} </li>
<li>
<button onClick={clickFilter}>Добавить в корзину</button> //при нажатии этой кнопки добавление в корзину
</li>
</ul>
</div>
);
const BASE_PATH = 'https://api.punkapi.com/v2/beers';
class Store extends Component {
state = {
result: [],
buy:[],
}
componentDidMount() {
fetch(`${BASE_PATH}`)
.then(res => res.json()) //это работает
.then(result => this.setItem(result))
.catch(error => error);
}
setItem = result => {
this.setState( {result} );
}
render() {
const { result } = this.state;
return (
<div>
<ul >
{result.map(({ id, name, tagline, abv, description, image_url}) => // вытягивание полученных с
<NewsItem key={id} // АПИ данных и их стилизация
styles={'item'}
image={image_url} // NewsItem - компонент для стилизации
id={id}
name={name}
tagline={tagline}
abv = {abv}
// clickFilter = {здесь нужна реализация метода для добавления в корзину}
/>
)}
</ul>
</div>
)
}
const NewsItem = ({ styles, ...остальные пропсы}) => (
<div >
<ul className={styles}>
...код дальше
</div>
Answer the question
In order to leave comments, you need to log in
1. What's with the names? NewsItem, setItem, result, clickFilter, styles, buy - never write something like this even as a joke. Replace: NewsItem with Product(or ShopItem), setItem - delete altogether, result with products, clickFilter with handleAddToCartClick, styles with className, buy with cart.
2. There is no point in passing each product property to ShopItem separately. You only make it harder to analyze your code. It is better:
{products.map(product => (
<ShopItem
key={product.id}
className={'item'}
item={product}
onAddToCartClick={this.handleAddToCartClick}
/>
)}
const BASE_PATH = 'https://api.punkapi.com/v2';
/* ... */
fetch(`${BASE_PATH}/beers`)
How to add the received "goods" to the cart? I was not able to use the values from state.result to add them to state.basket later.
result is just an array of objects. You can access any product using this.state.result[object_index], but I can’t do anything with this data directly, just like using setState
class Store extends Component {
state = {
products: [],
cart:[],
};
handleAddToCartClick = (id, quantity) => {
const { cart } = this.state;
const itemIndex = cart.findIndex(item => item.id === id);
if (itemIndex !== -1) {
const newCart = [...cart];
newCart[itemIndex] = { id, quantity: cart[itemIndex].quantity + quantity };
this.setState({ cart: newCart });
} else {
this.setState(prevState => ({
cart: [
...prevState.cart,
{ id, quantity },
],
}));
}
};
const ShopItem = ({ className, item, onAddToCartClick }) => (
<div>
{/* ... */}
<button onClick={() => onAddToCartClick(item.id, 1)}>Добавить в корзину</button>
<div/>
);
I wanted to create a button for each "product" that will change the style of this SPECIFIC product (this does not carry any semantic load, but I wanted to implement it in order to understand some things).
My NewsItem component has a styles prop that sets the style to the component.
import React, { useState } from 'react';
const ShopItem = ({ className, item, onAddToCartClick } ) => {
const [isActive, setIsActive] = useState(false);
handleToggleActiveClick = () => {
setIsActive(!isActive);
};
return (
<div>
<ul className={`${className}${isActive ? ' active' : ''}`}>
{/* ... */}
<button onClick={handleToggleActiveClick}>Toggle active</button>
</ul>
<div/>
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question