What is the right construction to print this JSON data in React?

82 Views Asked by At

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.

1

There are 1 best solutions below

2
Martin Gainza Koulaksezian On

You are trying to do the map before the boardData is updated.

because of this:

constructor(props) { super(props);

    // Default state
    this.state = {
      settings: {},
      name: "",
      boardData: {groups: []}
    };
  } 

In your code:

const navItems = this.state.boardData.boards.map((title) =>
  <a className="pageview__nav-item">{JSON.stringify(title, null, 2)}</a>
);

this.state.boardData.boards doesn't exists and you get the error:

TypeError: Cannot read property 'map' of undefined

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:

{ "boards": [ { "groups": [ { "title": "Introduction" }, { "title": "Page Two" } ] } ] }

You will need a map for each board an another map for each group inside the board to access to the titles

return(
    <>
    {this.state.boardData.boards ? this.state.boardData.boards.map((group) =>
          <div className="groupContainer">
          {
            group.map(title=>
              <a className="pageview__nav-item">{title}</a>
            )
          }
          </div>
          }): null}
    </>
)