I'm getting data as an 'array of arrays', so I have to change it to an 'array of objects' so I can use it on my products page.
In the main products page, I am transforming it correctly, and using console.log, I can correctly see the 'array of objects'. After I pass down this 'array of objects' to my product page so I can use the data in the 'array of objects', the individual objects are rearranged and messed up. I've been trying to understand what went wrong but I cannot debug this. Please help.
My products page:
import React, { useState } from "react";
import Product from "./Product";
function Products() {
//State management for the data pulled using fetch
// data comes in as an array of arrays
// so I have to transform into an array of objects
const [data, setData] = useState([]);
// using the first array in the 'array of arrays' as keys
const keys = data.shift();
// transforming from 'array of arrays' to 'array of objects'
const dataObj = data.map(elem => ({
[keys[0]]: elem[0],
[keys[1]]: elem[1],
[keys[2]]: elem[2],
[keys[3]]: elem[3],
}));
console.log(dataObj)
// pulling data from excel sheet
const getData = () => {
fetch(
"https://sheets.googleapis.com/v4/spreadsheets/1DpaMUmqYxGUKnT9BL0uBuCZ6WJ8vd1CLAklqUvkcA8M/values/Sheet1?alt=json&key=AIzaSyD6o4v215zWtw-kOqGVeuLG50pE2QeRZTg",
{
method: "GET",
}
)
.then((response) => response.json())
.then((data) => {
// console.log(data.value);
setData(data.values);
});
};
return (
<div>
Hello, you're in the products page
<button onClick={getData}>click me</button>
{dataObj.map((prod) => (
<Product prod={prod} key={prod.id}/>
))}
</div>
);
}
export default Products;
My products page
import React from "react";
function Product(props) {
console.log(props.prod);
return (
<div>
</div>
);
}
export default Product;
Ignore the empty array pls. The first array is my 'array of objects' and it is arranged properly, but the other parts are the individual objects and they are messed up.
Edit: data.value
CodePudding user response:
shift
is a mutation. Never ever ever ever ever ever mutate things in react.