Reputation: 76
const mongoose = require("mongoose")
const productSchema = mongoose.Schema(
{
title:{
type: String,
required: true,
unique: true
},
description:{
type: String,
required: true
},
img:{
type: String,
required: true
},
categories:{
type: Array
},
size:{
type: String
},
color:{
type: String
},
price:{
type: Number,
required: true
},
inStock:{
type: Boolean, default: true
}
},
{timeStamps: true}
)
module.exports = mongoose.model("Product", productSchema)
I have a problem in mapping product properties like color and size.
Product data is received from the backend using Axios but the useEffect
is not re-rendering and the product objects like color and size are not present at the first load of the component. They are undefined because of which .map
is not a function error is showing
const location = useLocation()
const id = location.pathname.split("/")[2]
const [product, setProduct] = useState({})
useEffect(() =>{
console.log("useEffect")
const getProduct = async ()=>{
try{
const res = await publicReq.get("/products/find/" + id)
console.log(res.data)
setProduct(res.data)
console.log("useEffect worked")
console.log(product)
console.log(product.color)
console.log(product.size)
console.log(product.title)
}catch (err){
console.log(err)
console.log("not running")
}
}
getProduct()
}, [id])
<Filter>
<FilterTitle>{console.log("running")}Color</FilterTitle>
{product.color?.map((c) =>{
console.log("lo running")
return(
<Color color={c} key={c} onClick={() => setCol(c)}/>
)
})}
</Filter>
Upvotes: 0
Views: 657
Reputation: 76
(Solved) The error is I didn't initialize the product.color in Array type instead and the .map() function works only on Arrays.
color:{ type: Array },
this should be the code of color in mongoDB Schema
Upvotes: 0
Reputation: 1331
.map
only works on arrays. Check if your product.color
data is in the form of an array. An easy way to check is by doing console.log(Array.isArray(products.color))
In addition, it wouldn't hurt to initialize your product state as the form of the data you're receiving , so no type errors or bugs occur on a component's mount. Below is an example.
const [product, setProduct] = useState({size: "", title: "",color: []})
function isArray(arr){
return Array.isArray(arr)
}
console.log(isArray([]))
console.log(isArray([1,2,3]))
console.log(isArray("no"))
console.log(isArray("[]"))
Upvotes: 1