Categories

Thursday, November 21, 2024
#919814419350 therichposts@gmail.com
Bootstrap 5JavaReactjsSpring Boot

How to fetch spring boot web api data in reactjs using useState useEffect hook?

How to fetch spring boot web api data in reactjs using useState useEffect hook?

Hello friends, welcome back to my blog. Today in this blog post, I am going to show you, How to fetch spring boot web api data in reactjs using useState useEffect hook?


Working Demo

How to fetch spring boot web api data in reactjs using useState useEffect hook?
How to fetch spring boot web api data in reactjs using useState useEffect hook?
Spring Boot WEB API JSON DATA
Spring Boot WEB API JSON DATA

For reactjs new comers, please check the below link:

Reactjs Basic Tutorials

Bootstrap 5 Tutorials

Spring Boot


Friends now I proceed onwards and here is the working code snippet and please use this carefully to avoid the mistakes:

1. Firstly, we need fresh reactjs setup and for that, we need to run below commands into out terminal and also we should have latest node version installed on our system and bootstrap as well:

npx create-react-app reactdemo

cd reactdemo

npm install bootstrap

npm i @popperjs/core

npm start

2. Finally for the main output, we need to add below code into our reactdemo/src/App.js file or if you have fresh setup then you can replace reactdemo/src/App.js file code with below code:

// 1. Import *useState* and *useEffect*
import React, {useState, useEffect} from 'react';
import "bootstrap/dist/css/bootstrap.min.css"

function App() {
    // 2. Create our *data* variable as well as the *setdata* function via useState
    // We're setting the default value of data to null, so that while we wait for the
    // fetch to complete, we dont attempt to render the data
  let [data, setdata] = useState(null)

    // 3. Create out useEffect function
  useEffect(() => {
    fetch("http://localhost:8080/json/employees")
    .then(response => response.json())
        // 4. Setting *data* to the API DATA that we received from the response above
    .then(data => setdata(data))
  },[])

  return (
    <div className="App container py-5">
    
      <table class="table">
        <thead>
          <tr>
            <th scope="col">#ID</th>
            <th scope="col">First Name</th>
            <th scope="col">Last Name</th>
            <th scope="col">Age</th>
            <th scope="col">Salary</th>
          </tr>
        </thead>
        <tbody>
         
          {data && (data.map(item =>
            <tr>
              <th scope="row">{ item.id }</th>
              <td>{ item.firstName }</td>
              <td>{ item.lastName }</td>
              <td>{ item.age }</td>
              <td>{ item.salary }</td>
            </tr>
            ))}
        </tbody>
      </table>
    </div>
  );
}

export default App;

3. Here is my spring boot controller file code where I made the web api:

package io.java.isthesiteup.controllers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import io.java.isthesiteup.model.Employee;

@Controller
@CrossOrigin(origins = "http://localhost:3000/")
@RequestMapping(value = "/json")
public class JsonResponseController {

  @RequestMapping(value = "/employees", method = RequestMethod.GET, produces = "application/json")
  public @ResponseBody List<Employee> getAllEmployee() {

    // We will set some dummy data and send it as response
    List<Employee> employees = new ArrayList<Employee>();

    Employee empl1 = new Employee("001", "Jassa", "Mann", 25, 5000d);
    Employee empl2 = new Employee("002", "Jas", "malhotra", 22, 4500d);
    Employee empl3 = new Employee("003", "Harjas", "D", 27, 6000.50);

    employees.add(empl1);
    employees.add(empl2);
    employees.add(empl3);

    return employees;
  }
}

Now we are done friends. If you have any kind of query or suggestion or any requirement then feel free to comment below.

Note: Friends, I just tell the basic setup and things, you can change the code according to your requirements.

I will appreciate that if you will tell your views for this post. Nothing matters if your views will be good or bad.

Jassa

Thanks

therichpost
the authortherichpost
Hello to all. Welcome to therichpost.com. Myself Ajay Malhotra and I am freelance full stack developer. I love coding. I know WordPress, Core php, Angularjs, Angular 19, MedusaJs, Next.js, Bootstrap 5, Nodejs, Laravel, Codeigniter, Shopify, Squarespace, jQuery, Google Map Api, Vuejs, Reactjs, Big commerce etc.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.