Search code examples
javascriptreactjsfetchjson-server

mapping return data from a fetch call to state causing error


I am attempting to use a direct fetch to JSON.server to retrieve a basic package to load some simple components. When I run this script in Firefox. I get a "Network Error when attempting to fetch the resource" but cannot find any 400 errors in the network connection itself. My question is, what would cause this kind of breakdown? as the rest of the page loads fine when called.

Edit 1: it is specifically stating that data.StatusComponent is undefined.

  import React, { Component } from 'react';
import '../HeaderBar/HeaderBar.css';
import 'whatwg-fetch';
type StatusBarProps = {};
type StatusBarState = {
    launch_timer: boolean;
    foreGroundTimer: number;
    // tslint:disable-next-line:no-any
    statusBarBlocks: any;
};
class StatusBar extends Component<StatusBarProps, StatusBarState> {
    timerId: number;
    constructor() {
        super();
        this.state = {
            launch_timer: true,
            foreGroundTimer: -1,
            statusBarBlocks: []
        };
    }
    componentDidMount() {
        fetch('http://localhost:5001/StatusComponent').then(results => {
            return results.json();
        }).then(data => {
            let systemOff = 'green';
            let systemOn = 'gray';
            let statusBarBlocks = data.StatusComponent.map((Status) => {
                return (
                    <div className="blockBar" id={Status.id} key={Status.key} style={{ backgroundColor: (this.state.foreGroundTimer >= Status.id) ? systemOff : systemOn }}> {Status.Name} </div>
                );
            });
            this.setState({ statusBarBlocks: statusBarBlocks });
        });
    }
    componentWillUnmount() {
        clearInterval(this.timerId);
    }
    tick() {
        this.setState({ launch_timer: !this.state.launch_timer, foreGroundTimer: (this.state.foreGroundTimer + 1) % 26 });
    }
    render() {

        return (
            <div className="location">
                <div className="col-xs-6">
                    {this.state.statusBarBlocks}
                </div>
            </div>
        );
    }
}
export default StatusBar;

Solution

  • If data.StatusComponent is undefined, then either data is undefined or there is no StatusComponent property on data. console.log(data) to verify.