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

231
Vistas
How do I map data from state to component prop?

To start with I'm a beginner. Any help would be appreciated. So I'm getting my data from mongoDB atlas using node+express API. I'm successfull at getting the array to show up in console log using following code.

const [product, setProduct] = useState();
    const url = "http://localhost:5000/api/items";

    useEffect(() => {
        axios.get(url).then((res) => {
            setProduct(res.data);
            // setProduct(
            //     JSON.stringify({
            //         title: setProduct.title,
            //         price: setProduct.price, 
            //         image: setProduct.image,
            //         details: setProduct.details,
            //     })
            // );
        })
    }, [url])
    console.log(product)

The console log displays the array properly as collection named 'items' with content of arrays. As you can see I tried to stringify the response as the response returns JSON but again I didn't know how to map Following is the code where I tried to map the contents like id, name etc as props to component.

              <div>
                  {product.map((product) => {
                          <Product name={product.title} />
                  })}
              </div> 

When I do this I get error that the map is not a function. I don't know what I'm doing wrong here. I know I'm supposed to use redux or reducer/context here but I want to get this to work before updating it with those.

[![Response from res.data][1]][1] [1]: https://i.stack.imgur.com/auxvl.png

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

0

On the first render the value for types will be undefined ( on sync code execution ), try using it as

<div>
   {product?.map((product) => {
   <Product name={product.name} />
   })}
   </div> 

? will make sure to run map once value for types is there ( also make sure it is mappable ( is an array ))

about 4 years ago · Juan Pablo Isaza Denunciar

0

you didnt get yours products.

As we can see from screenshot

res.data equal to object with one property items: res.data= {items: []} and we need to take/access to these items

use this: setProducts(res?.data?.items || [])

const [products, setProducts] = useState();
    useEffect(() => {
        axios.get(url).then((res) => {
            setProducts(res?.data?.items || []);
        })
    }, [url])
              <div>
                  {products?.map((product) => {
                          <Product name={product.title} />
                  })}
              </div> 
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