Search code examples
javascriptreactjsobjectreact-hooksfetch

Fetched object returns underfined


I have my data objects that I need to fetch, looking like this:

const products = {
        one: {
            id: 1,
            name: 'One',
            image: oneImage,
            chair: {
                name: 'ChairName',
                image: myImage,
                colors: {
                    white: {
                        name: 'White',
                        image: myImage,
                    },
                    black: {
                        name: 'Black',
                        image: myImage,
                    },
                },
            },            
            },
        },
        two: {
            id: 2,
            name: 'Two',
            image: twoImage,
            chair: {
                name: 'Chair,
                image: myImage,
                colors: {
                    white: {
                        name: 'White',
                        image: myImage,
                    },
                    black: {
                        name: 'Black',
                        image: myImage,
                    },
                },
            },
        },
    };

I am fetching them with Object.value

const ProductsData = Object.values(products).map((data) => {

    return (
        <>
            <div className="box" onClick={() => setSelectedData(data)}>
                 <img src={data.image} />
            </div>
           );
});

This code above works just fine, pointing out to selected data like this:

           {selectedData ? (
              <h1>{selectedData.name}</h1>
           ) : null}

But now I would like to map through the chair colors of selected Data, which causes errors.

What I tried to do was to just {selectedData.chair.colors.name}, which prints nothing and by console.log is underfined

How can I print selectedData of chair colors and how I can set the picked color as new selectedData? I am getting lost.


Solution

  • If you want to choose color, then you need to store it in another state variable.

      const [selectedColor, setSelectedColor] = React.useState();
    

    Use Object.values to iterate chair.colors

      {Object.values(selectedData.chair.colors).map(val => {
        return <div onClick={() => setSelectedColor(val.name)}>{val.name}</div>
      })
       }
    

    Check this sandbox