Home > Mobile >  How to correctly fetch data from an API with React?
How to correctly fetch data from an API with React?

Time:12-13

I am trying to fetch some data from a local API but I am getting the following error:

enter image description here

The API is working fine as I tested here:

enter image description here

I am trying to fetch the data like this:

export class WhereWeFly extends Component {

    componentDidMount(){
      fetch("http://127.0.0.1:3001/api/content/home")
      .then((response) => response.json())
      .then((data) => this.setState({markerProps: data}));
    }

    state = {
        markerProps: {},
        activeMarker: {},          
        selectedPlace: {},
        //Polyline variables
        clicked: false,
        index: 0,
        routes: []
    };

Code where the error happens:

       <Map
            google={this.props.google}
            zoom={zoom}
            style={mapStyles}
            initialCenter={initCenter}>
        
            {this.state.markerProps.Items.map(item =>
                <Marker
                    onClick={this.onMarkerClick}
                    name={item.id}
                    position={{lat: item.coordinates.lat, lng: item.coordinates.lng}}
                />)}

What am I missing here? Thank you!

CodePudding user response:

You can fix the problem by providing Items in the marketProps, when you want set the intial value of your state, like this:

state = {
    markerProps: { Items: [] },
    activeMarker: {},          
    selectedPlace: {},
    //Polyline variables
    clicked: false,
    index: 0,
    routes: []
};
  • Related