Saturday, April 23, 2022

ReactJS Part 8 .Net Core React - Connecting to Web API - Fetch API GET

The blog is a continuation of ReactJS Part 7 .Net Core React Project.

 In the blog Angular with .Net Core 3 and Visual Studio Code I have discussed creating Web API with .Net 5 CLI. 

Program.cs

using corereact.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllersWithViews();
builder.Services.AddScoped<ContactManagementContext>();
Scaffolded Web API Core Controller code.
#nullable disable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using corereact2.Models;

namespace corereact2.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class GroupsController : ControllerBase
    {
        private readonly ContactManagementContext _context;

        public GroupsController(ContactManagementContext context)
        {
            _context = context;
        }

        // GET: api/Groups
        [HttpGet]
        public async Task<ActionResult<IEnumerable<Group>>> GetGroups()
        {
            return await _context.Groups.ToListAsync();
        }

        // GET: api/Groups/5
        [HttpGet("{id}")]
        public async Task<ActionResult<Group>> GetGroup(int id)
        {
            var @group = await _context.Groups.FindAsync(id);

            if (@group == null)
            {
                return NotFound();
            }

            return @group;
        }

        // PUT: api/Groups/5
        [HttpPut("{id}")]
        public async Task<IActionResult> PutGroup(int id, Group @group)
        {
            if (id != @group.GroupId)
            {
                return BadRequest();
            }

            _context.Entry(@group).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!GroupExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/Groups
        [HttpPost]
        public async Task<ActionResult<Group>> PostGroup(Group @group)
        {
            _context.Groups.Add(@group);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetGroup", new { id = @group.GroupId }, @group);
        }

        // DELETE: api/Groups/5
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteGroup(int id)
        {
            var @group = await _context.Groups.FindAsync(id);
            if (@group == null)
            {
                return NotFound();
            }

            _context.Groups.Remove(@group);
            await _context.SaveChangesAsync();

            return NoContent();
        }

        private bool GroupExists(int id)
        {
            return _context.Groups.Any(e => e.GroupId == id);
        }
    }
}

ReactJS Home.js
import React, {useState, useEffect } from 'react';

export function Home(){
  let [groupsData, setGroupsData] = useState([]);

  const populateGroupData = async () => {
    const response = await fetch('api/groups');
    const data = await response.json();
    return data;
}

useEffect(() => {
  populateGroupData()
      .then(data => setGroupsData(data));
}, []);

  return (
      <div>
        <h1>Groups</h1>
        <table className='table table-striped'>
                <thead>
                    <tr>
                        <th>Name</th>
                        <th>Details</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody>
                    {groupsData.map(group =>
                        <tr key={group.groupId}>
                            <td>{group.groupName}</td>
                            <td>{group.description}</td>
                        </tr>
                    )}
                    
                </tbody>
            </table>
      </div>
    );
  }



No comments:

Post a Comment