This is my App.js
:
<Provider store={store}>
<Header />
<Routes>
{ categories.map(({ category }) => {
return (
<Route
key={name}
exact path={`/${category}`}
element={<Category name={name} />}
/>
)
}) }
</Routes>
</Provider>
Category.jsx
:
export class Category extends Component {
render() {
const { name } = this.props;
return (
<div>
<h1>{name}</h1>
<CategoryBody name={name} />
</div>
);
}
}
export default Category;
CategoryBody.jsx
:
export default class CategoryBody extends Component {
constructor() {
super();
this.state = {
products: [],
};
}
componentDidMount() {
const path = window.location.pathname;
const selectedCategory = path === "/" ? "all" : path.split("/")[1];
client
.query({
query: PRODUCTS_QUERY,
variables: { title: `${selectedCategory}` },
})
.then((result) =>
this.setState({ products: result.data.category.products })
);
}
render() {
const { products } = this.state;
return (
<div className="category-container">
{products.map(({ id, name, inStock, gallery, prices, brand }) => {
return (
<ProductCard
key={id}
id={id}
name={name}
inStock={inStock}
gallery={gallery}
prices={prices}
brand={brand}
/>
);
})}
</div>
);
}
}
This is working fine when I change routes reloading the page. But when I change routes through nav links in my Header, the props name
is updated, but the rest of the application is not.
Specifically, the API call in componentDidMount()
of CategoryBody.jsx
is needed to be called again so that the items rendered in the component are the expected, according to the path.
I would like to know how can I “force update” a component when I change routes from inside the application.