0

Sorry if the titel was a bit of or bad.

But the thing is that im fetching from my db and im using map to display each product and i have a selectionbox inside the rendered product where im trying to map from an array in the db.

Im fetching like this:

fetch('/api/products')
    .then(res => res.json())
    .then(allProducts => {
        this.setState({ allProducts });
});

My map look like this:

{
this.state.allProducts.map(allProducts =>
                            
  <div className="products" key={allProducts.produkt_id}>
                                
  <select name="format">
    <option value="choose_format">choose format</option>
                                        
  </select>

</div>
)
}

And in my db the array is stored like this in a column:

[{"car":"audi"},{"car":"bmw"}]

How do i map out the different cars as options or im i doing something wrong and can i store it in a better way?

1 Answer 1

1
{ produkt_id: "123", car: "bwm" , color: [{"color":"audi"},{"color":"bmw"}]} 

Your render would then be:

return this.state.allProducts.map((product) => (
    <div className="products" key={product.produkt_id}>
      <select name="format">
        {product.color.map((colorOption) => (
          <option value={colorOption.color}>{colorOption.color}</option>
        ))}
      </select>
    </div>
  ));
Sign up to request clarification or add additional context in comments.

4 Comments

{ produkt_id: "123", car: "bwm" , color: [{"color":"red"},{"color":"white"}]} maybe color in the array i can remove later so it doesnt have to say color twice but this is a better example how i have it now and i want the options to display every color of the car, how can i do that?
im trying your solution but im getting "TypeError: product.color.map is not a function", do you know why?
Tells you color is not a array, so it does not have a .map function. Debug with console.log.
Thank you very much, had use JSON.parse(), instead of product.color.map i had to use JSON.parse(product.color).map

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.