Home > front end >  How do I map data from state to component prop?
How do I map data from state to component prop?

Time:04-09

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

CodePudding user response:

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> 

CodePudding user response:

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 ))

CodePudding user response:

**Just put the initial state to be an empty array and also use ?. which is latest es js. **

const [product, setProduct] = useState([]);
 useEffect(() => {
    axios.get(url).then((res) => {
        setProducts(res.data?.items);
    })
}, [url])
    
   {product?.map((product) => {
      return (<Product name={product.name} />)
   })}
  
  • Related