I'm trying to fetch data for a React component and set it as a nested object in state:
import React from 'react';
import './App.css';
import XLSX from "xlsx";
class App extends React.Component {
constructor(props){
super(props);
this.state = {
isLoading:false,
cards:{}
}
}
componentDidMount(){
this.setState({isLoading:true});
/* convert xlsx to JSON */
fetch("../data/Cards_v0.1.xlsx")
.then((d)=> d.arrayBuffer()).then((d)=>{
const data = new Uint8Array(d);
const workbook = XLSX.read(data, {type:"buffer"});
const sheet = workbook.Sheets["Deck"];
const cardsJSON = XLSX.utils.sheet_to_json(sheet,{range:1});
let cards = {};
for(let i=0; i<cardsJSON.length; i++){
for(let j=0; j<cardsJSON.length; j++){
cards[cardsJSON[i].Name] = cardsJSON[i];
}
}
this.setState({cards:cards, isLoading:false});
});
}
render() {
if(this.state.isLoading){
return <div>Loading</div>;
}
return (
<div>
{ this.state.cards.Single.Name }
</div>
);
}
}
export default App;
React devtools shows that the object is in state, with cards>Single>Name being "Single", but {this.state.cards.Single.Name} throws TypeError: Cannot read property 'Name' of undefined.
What's confusing me most is that {this.state.cards.Single} instead throws Objects are not valid as a React child (found: object with keys {Name, Type, Rarity, Text, Money}). If you meant to render a collection of children, use an array instead.
So the key Name is found when it's not being called, but then the object becomes undefined when I call it?
Very confused. Any help is appreciated!