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

200
Visualizações
Cannot read properties of undefined (reading 'map') I can't use my variable again

I had confused by this kind of error despite I had used the self variable products to display all my products but when I try to use it again I can't catch it noted that variable I got it by calling Axios by redux. why I didn't know: so this is my code:

import React, {useEffect} from "react";
import Product from "../components/Product";
import LoadingBox from "../components/LoadingBox";
import AlertBox from "../components/AlertBox";
import {useSelector, useDispatch} from "react-redux";
import {listProducts} from "../actions/productAction";



const HomePage = () => {
    const dispatch = useDispatch();
   
    useEffect(()=> {
     dispatch(listProducts()); 
     
     }, [dispatch])
     const productsList = useSelector((state) => state.productsList);
    
   const {products, loading, error} = productsList;

console.log(products)
const categories = products.map((x)=> x.subCategory);
console.log(categories)
    return (
 <div>
       
            {loading? (<LoadingBox></LoadingBox>):error? (<AlertBox variant="danger" >{error}</AlertBox>):(
                <div className="row center" >
                 {
                    products.map((product) => (
                     <Product key={product._id} product={product} ></Product>
                    ))}
                    </div>
            )}
                 
            </div>             
    )

};
export default HomePage;
about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

The map function is only used to iterate an array. If any other type of data is been sent into products then use the following exception to not produce a crash or error.

Syntax

array.map((item, index) => {
  //code
})

Your representation

<div className="row center" >
   {products?.map((product) => (
       <Product key={product._id} product={product} ></Product>
   ))}
</div>
about 4 years ago · Santiago Gelvez Relatório

0

I bet you initialize your store state.productsList with null, thus you have to check if products really fetched or provide default value for productsList.

const categories = products?.length 
 ? products.map(({subCategory})=> subCategory)
 : [];
about 4 years ago · Santiago Gelvez Relatório

0

The thing you are missing is short circuiting. When you use redux thunk as a middleware or any asynchronous way to fetch the data from server,then you have to make sure each node of the object which you want to render should be found. It is because at the very first miliseconds the data is not already fetched but react tends to render the data which will obviously null or undefinded as the data is not fetched yet.

This can be solved in two different ways with short circuiting.

1. Pass the deepest node or make sure the length of products is not 0 by passing it in a dependency array as:

useEffect(()=> {
     dispatch(listProducts()); 
     
     }, [dispatch,products?.length])

2.

{products?.products.map((product) => (
       <Product key={product._id} product={product} ></Product>
   ))}

for more refrerence,you can look at:short-circuiting-evaluation in javascript

about 4 years ago · Santiago Gelvez 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