Answer the question
In order to leave comments, you need to log in
How to organize the Category Page component?
Good morning, there is a component "Product category page"
in useEffect I do fetch /api/category/:category , which returns:
{
title: 'Мобильные телефоны',
h1: 'Мобильные телефоны в Уфе',
products: [
{ ... },
{ ... },
...
],
...
}
const CategoryPage = ({ categorySlug }) => {
const [page, setPage] = useState(0);
useEffect( () => {
fetch(`/api/category/${categorySlug}`)
.then( (res) => res.json())
.then( (res) => setPage(res));
}, []);
return (
<>
<h1>{page.h1}</h1>
<ProductListContainer products={page.products} categorySlug={categorySlug} />
</>
);
};
const ProductListContainer = ({ products, categorySlug }) => {
const [productsList, setProducts] = useState(products); // Не уверен что так можно.
useEffect( () => {
if(productsList.length === 0) {
fetch(`/category/${categorySlug}/products`)
.then( (res) => res.json())
.then( (res) => setProducts(res));
}
}
, []);
const loadProducts = ({ page, count }) => {
fetch(`/api/category/${categorySlug}/products?page=${page}&count=${count}`)
.then( (res) => res.json())
.then( (res) => setProducts(res));
};
return <ProductList products={productsList} loadProducts={loadProducts}/>;
};
const MyComponent = ( props ) => {
const [count, setCount] = useState(props.count); // записывать в state из props
}
Answer the question
In order to leave comments, you need to log in
Since they asked:
1. What does "correctly" mean? it's normal for you to organize
2. to call something a container or not is your own business, depending on how you decide to organize the code for yourself. there are no requirements and generally accepted standards that cannot be violated in this regard.
3. in the general case - it is better to load the data somewhere in one place. But there are exceptions, whether it's bad with you or not here - I don't know. Maybe there are fewer requests to the server or better code - then it's not bad. If you just didn't know how to organize the code and copy-pasted the download into two places, then it's bad.
4. you can
x. If there is no need for an editor, then yes, it is not needed. If the code starts to get complicated, some application state will be required.
PS. you can look at apollo-client, it has redax inside like. But you hardly have to write such a library plan.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question