Problem with rendering data from backend React js, Spring HATEOAS

I have a problem with fetching data from the backend. when I try to render data from the backend I have the error

Portfolio.js:34 Uncaught TypeError: Cannot read properties of undefined (reading 'self')
at Portfolio.render (Portfolio.js:34:1)
at finishClassComponent (react-dom.development.js:17485:1)
at updateClassComponent (react-dom.development.js:17435:1)
at beginWork (react-dom.development.js:19073:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:3945:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:3994:1)
at invokeGuardedCallback (react-dom.development.js:4056:1)
at beginWork$1 (react-dom.development.js:23964:1)
at performUnitOfWork (react-dom.development.js:22776:1)
at workLoopSync (react-dom.development.js:22707:1)

The code

    import React, { Component } from 'react'
import { Card } from 'react-bootstrap'
import { Row } from 'react-bootstrap'
import { MDBCard, MDBCardImage, MDBCardBody, MDBCardTitle, MDBCardText, MDBRow, MDBCol, MDBContainer, MDBRipple, MDBCardOverlay, MDBCardLink } from 'mdb-react-ui-kit';
import axios from 'axios';
import { ThemeConsumer } from 'react-bootstrap/esm/ThemeProvider';


export default class Portfolio extends Component {
  
  constructor(props){
    super(props);
    this.state={
          photoAlboums:[]
    };
  }

  componentDidMount(){
    axios.get("http://localhost:8081/api/photo-albums/1")
    .then((response) => {
      this.setState({photoAlboums: response.data});
    })

  }

  render() {
    return (
     <div>
       <p>{this.state.photoAlboums._links.self.href}</p>
    </div>
    )
  }
}

The data

{"id":1,"name":"Photo studio","_links"
:{"self":{"href":"http://localhost:8081/api/photo-albums/1"},
"photoAlbums":{"href":"http://localhost:8081/api/photo-albums/list"}}}

But when I render the name of data, everything works. How to solve this problem? Thanks!

1 answer

  • answered 2022-05-04 11:43 Munei Nengwenani

    The issue here is that you are trying to get data out of an array as an object. you will need to update you code to be able to take in the array items. see example below.

    Change your code to:

    {this.state.photoAlboums.length > 0 && 
      this.state.photoAlboums.map((photo) => {
        <div>
          <p>{photo._links.self.href}</p>
        </div>
    
     } )
    

    Also check your typos.

How many English words
do you know?
Test your English vocabulary size, and measure
how many words do you know
Online Test
Powered by Examplum