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
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 theisDataFetched
is still empty, the "Loaging…" paragraph will be showed. After the request is finished and thetodos
value is updated, another re-rendering is triggered, and this time, the list with the todo items will be displayed.I hope it helps you a little bit!
Create React App: First, create a new React app using Create React App. Open your terminal and run:
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:
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:
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:
Run Your React App: Finally, run your React app:
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.