skip to Main Content

I am running my spring boot application on port 8080 and have set up a react app on visual code. I created a proxy for the connection. I am using render() to have a ‘Loading’ piece pop up as the information is grabbed but its stuck at Loading and I dont know why.

Here is the Category.js

import React, { Component } from 'react';

class Category extends Component {

    state = {
        isLoading : true,
        Categories : []
    }

     async componentDidMount(){
        const response = await fetch('/api/categories');
        const body = await response.json();
        this.setState({Categories :body, isLoading: false});
        }
     render(){ 
        const{Categories, isLoading} = this.state;
        if(isLoading)
            return(<div>Loading......</div>);
        
        return (
            <div>
                <h2>Categories</h2>
                {
                    Categories.map( category =>
                    <div id={category.id}>
                        {category.name}
                    </div>
                    )
                }
            </div>
        );
    }
}
 
export default Category;

And…… Here is the index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import Category from './Category';

import reportWebVitals from './reportWebVitals';
//import * as serviveWorker from './serviceWorker';

//ReactDOM.render(<Category/>, document.getElementById('root'));
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <Category/>
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))

reportWebVitals();
//serviveWorker.unregister();

I am trying to get passed this loading state and show the actual categories.

2

Answers


  1. It could be that your API is not working property so it does not change the the state. You can test it by console logging the response (or the body variable). I’m not sure you can just fetch like that. Also I recommend you to use a new React approach such as using hooks and Functional Components more than classes.

    Login or Signup to reply.
  2. I think may be an issue with the url used in fetch(). if the proxy isn’t working as expected try this instead: since your server runs on 8080 it should be fetch('http://localhost:8080/api/categories'). Do check the network tab in the developer console on chrome or Firefox will let you know if the request is successful or not

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search