Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

327
Visualizações
.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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda