skip to Main Content

I have a Spring Boot backend that outputs certain Json data upon certain GET or POST requests.

Is there a simple tutorial for creating a react .js/.css combination to create a request through a button, interpret the Json response and display it?

(Right now I have to manually enter the HTTP GET request and I get a raw Json String response, that’s where I’m at…)

My Front-end knowledge has been slowly going down to near zero over the last years… And for some reason I can’t seem to find an easy example.

I have tried some Google / Youtube searches but the results that I get are using a Json file inside the React project for instance, that’s not what I’m looking for 😀

2

Answers


  1. Here is a simple example of a basic component that uses https://jsonplaceholder.typicode.com/todos/ to fetch and display some todo items when clicking on a button.

    The component needs 2 states. The first one is used to follow if the button was pressed or not. Initially, the button is not pressed, so the "Get Todo List" button is rendered. When we press it, the state is updated and the getTodos function is called. Since this function makes a request, it is an async function, which uses the fetch API to call the JsonPlaceholder endpoint, and updates the second state with the response data. The .json() method needs to be called to parse the data in a JSON format.

    After pressing the button, the value of isDataFetched is updated, and a re-rendering is triggered. This is why the button is not displayed anymore, and since the isDataFetched is still empty, the "Loaging…" paragraph will be showed. After the request is finished and the todos value is updated, another re-rendering is triggered, and this time, the list with the todo items will be displayed.

    import React, { useState } from "react";
    import "./App.css";
    
    export default function App() {
      const [isDataFetched, setIsDataFetched] = useState(false);
      const [todos, setTodos] = useState([]);
    
      async function getTodos() {
        try {
          const res = await fetch(`https://jsonplaceholder.typicode.com/todos/`);
          const todos = await res.json();
          setTodos(todos);
        } catch (err) {
          console.error(err);
        }
      }
    
      function handleClick() {
        setIsDataFetched(!isDataFetched);
        getTodos();
      }
    
      if (!isDataFetched) {
        return <button onClick={handleClick}>Get Todo List</button>;
      }
    
      if (todos.length === 0) {
        return <p>Loading...</p>;
      }
    
      return (
        <div>
          <ul>
            {todos.map((todoItem, index) => (
              <li key={index}>{todoItem.title}</li>
            ))}
          </ul>
        </div>
      );
    }
    

    I hope it helps you a little bit!

    Login or Signup to reply.
  2. Create React App: First, create a new React app using Create React App. Open your terminal and run:

    npx create-react-app my-app
    

    Replace my-app with the name of your application.

    Install Axios (Optional): You can use the fetch API directly, but many developers prefer using Axios for making HTTP requests due to its simplicity and features. Install Axios by running:

    npm install axios
    

    Create a Component: Create a new component in your React app. For this example, let’s create a component called DataFetcher.js. Inside src directory, create a new file DataFetcher.js with the following content:

    import React, { useState } from 'react';
    import axios from 'axios';
    
    const DataFetcher = () => {
      const [data, setData] = useState(null);
    
      const fetchData = async () => {
        try {
          const response = await axios.get('YOUR_API_ENDPOINT');
          setData(response.data);
        } catch (error) {
          console.error('Error fetching data:', error);
        }
      };
    
      return (
        <div>
          <button onClick={fetchData}>Fetch Data</button>
          {data && (
            <div>
              <h2>Data:</h2>
              <pre>{JSON.stringify(data, null, 2)}</pre>
            </div>
          )}
        </div>
      );
    };
    
    export default DataFetcher;
    

    Replace ‘YOUR_API_ENDPOINT’ with the actual endpoint of your Spring Boot backend.

    Use the Component: Now, import and use the DataFetcher component in your App.js file or any other component where you want to display the data. For example:

    import React from 'react';
    import DataFetcher from './DataFetcher';
    
    function App() {
      return (
        <div className="App">
          <h1>Spring Boot Data Fetcher</h1>
          <DataFetcher />
        </div>
      );
    }
    
    export default App;
    

    Run Your React App: Finally, run your React app:

    npm start
    

    This will start your React app, and you should be able to see a button labeled "Fetch Data". Clicking on this button will trigger an HTTP request to your Spring Boot backend, and the response will be displayed below the button.

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