Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

325
Vistas
.map Function React Hook useEffect not re rendering

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>
    
    

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

.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("[]"))

about 4 years ago · Juan Pablo Isaza Denunciar

0

(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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda