I'm new to React language and running into problem involving printing out of a given object/data-structure.
Data structure (JSON?)
{ "boards": [ { "groups": [ { "title": "Introduction" }, { "title": "Page Two" } ] } ] }
I'm at the point that I can print this.state.boardData.boards I found some topics about the map() functionalities but can't seem to get this to work.
My compentDidMount (involving the monday.api and GraphQL):
monday.listen("context", res => {
this.setState({context: res.data});
monday.api(`query ($boardIds: [Int]) { boards (ids:$boardIds) { groups { title } } }`,
{ variables: {boardIds: this.state.context.boardIds} }
)
.then(res => {
this.setState({boardData: res.data});
});
})
My map() function:
const navItems = this.state.boardData.boards.map((title) =>
<a className="pageview__nav-item">{JSON.stringify(title, null, 2)}</a>
);
Provided error:
TypeError: Cannot read property 'map' of undefined
I'm guessing this is because the values are empty when I'm trying to map the values. I tried to initialize the data but without luck:
constructor(props) {
super(props);
// Default state
this.state = {
settings: {},
name: "",
boardData: {groups: []}
};
}
I also tried to initialize the variable but that seems to complaining about variables already being declared.
Anyone can point me into the right direction? That would be really helpful.
You are trying to do the map before the boardData is updated.
because of this:
constructor(props) { super(props);
In your code:
this.state.boardData.boardsdoesn't exists and you get the error:Inside de return of the render you could do a validation before the use of the map so you make sure that array have values.
Following your JSON example data:
You will need a map for each board an another map for each group inside the board to access to the titles