I am trying to filter products by category id using react, redux and firestore. I am using firestoreConnect to query the products collection by the selected category id in a Link to statement - props.match.params.id and storing that query as filteredProducts.
This param id is not empty when console.log inside the render and firestoreConnect but in the where clause - it is not defined or null. Consequently, the query collection is empty and thus not retrieving any records.
Any solution will be appreciated.
I could output the props.match.params.id inside the firestoreConnect. Also, I have tried to index the firetore collection on firebase website without success.
Here is what I have in the products listing.js:
import React, { Component } from "react";
import { compose } from "redux";
import { connect } from "react-redux";
import { firestoreConnect } from "react-redux-firebase";
class Listing extends Component {
render() {
console.log(this.props.match.params.id); // able to log
const { filteredProducts } = this.props;
return (
<div>
{filteredProducts && filteredProducts.length > 0 ? (
<ul>
{filteredProducts.map(product => (
<li>{product.name}</li>
))}
</ul>
) : (
<div>no products matching criteria </div>
)}
</div>
);
}
}
const mapStateToProps = ({ firestore: { ordered } }) => ({
filteredProducts: ordered.filteredProducts
});
export default compose(
connect(mapStateToProps),
firestoreConnect(props => [
{
collection: "products",
where: ["category", "==", props.match.params.id],
storeAs: "filteredProducts"
}
])
)(Listing);`
and here is the list of dependencies in the package.json file
"firebase": "^5.11.1",
"react": "^16.6.3",
"react-dom": "^16.6.3",
"react-redux": "^5.1.1",
"react-redux-firebase": "^2.2.6",
"react-reveal": "^1.2.2",
"react-router-dom": "^5.0.0",
"react-scripts": "2.1.1",
"redux": "^4.0.1",
"redux-firestore": "^0.6.4",
"redux-thunk": "^2.3.0"
What I am trying to achieve is a filtered collection of products by a category id
what I am getting is null or undefined array object
As you are using the latest version of React Router (v4+), you have to wrap the whole component with the " withRouter " higher-order component. It will pass updated match, location, and history props to the wrapped component whenever it renders.
At first, you have to import the withRouter.
import { withRouter } from "react-router";
Then you have to wrap it with withRouter.
export default withRouter(compose(
connect(mapStateToProps),
firestoreConnect(props => [
{
collection: "products",
where: ["category", "==", props.match.params.id],
storeAs: "filteredProducts"
}
])
)(Listing));
Hope this helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.