I'm new to React with Redux and I've been working on a new web application that has some basic crud operations. I am building this using ASP.NET Core with a repository pattern.
My application is showing data correctly and I can also add data correctly, the problem I have is that updating my data isn't working. Whilst the data is passed into the controller, you can see the changes sitting in the parameter, once I try to commit the data it doesn't update.
My project is set up as follows, I've shortened certain parts it to only include the component I'm working with.
Shelly.Data
|-BaseEntity.cs
|-Vessel.cs
Shelly.Repo
|-IRepository.cs
|-Repository.cs
|-ShellyContext.cs
Shelly.Services
|-IVesselService.cs
|-VesselService.cs
Shelly.UI
|-ClientApp
|-src
|-components
|-vessels
|-VesselsComponent.js
|-store
|-Vessels.js
I've included the code from my repository in this question as I'm not convinced the issue is with my React setup but perhaps someone can help me with that.
Repo/IRepository.cs
public interface IRepository where TEntity : BaseEntity
{
IEnumerable GetAll();
TEntity Get(long id);
void Insert(TEntity entity);
void Update(TEntity entity);
void Delete(TEntity entity);
void Remove(TEntity entity);
void SaveChanges();
}
Repo/Repository.cs
public class Repository : IRepository where TEntity : BaseEntity
{
private readonly ShellyContext _dbContext;
private DbSet entities;
string errorMessage = string.Empty;
public Repository(ShellyContext context)
{
this._dbContext = context;
entities = context.Set();
}
...
public void Update(TEntity entity)
{
if (entity == null)
{
throw new ArgumentNullException("entity");
}
_dbContext.SaveChanges();
}
public void SaveChanges()
{
_dbContext.SaveChanges();
}
...
}
Services/IVesselService
public interface IVesselService
{
IEnumerable GetVessels();
Vessel GetVessel(long id);
void InsertVessel(Vessel vessel);
void UpdateVessel(Vessel vessel);
void DeleteVessel(long id);
}
Services/VesselService
public class VesselService : IVesselService
{
private IRepository vesselRepository;
public VesselService(IRepository vesselRepository)
{
this.vesselRepository = vesselRepository;
}
public void UpdateVessel(Vessel vessel)
{
vesselRepository.Update(vessel);
}
}
The next part is the controller which is called from react to carry out the CRUD operations and also serve up the data to the API. Reading and Added seem to work but Updating isn't, you can see the updated data being passed in vessel but it doesn't seem to commit and just refreshes with the old data.
Controllers/VesselDataController.cs
[Route("api/[controller]")]
public class VesselDataController : Controller
{
private readonly IVesselService vesselService;
public VesselDataController(IVesselService vesselService)
{
this.vesselService = vesselService;
}
...
[HttpPost]
public ActionResult AddVessel([FromBody]Vessel vessel)
{
vesselService.InsertVessel(vessel);
return Ok(new
{
success = true,
returncode = "200"
});
}
[HttpPut]
public ActionResult Update([FromBody]Vessel vessel)
{
vesselService.UpdateVessel(vessel);
return Ok(new
{
success = true,
returncode = "200"
});
}
}
Here is the code for my React/Redux configuration. Again, I've only included code for my relative component.
ClientApp/src/components/VesselsComponent.js
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { actionCreators } from '../../store/Vessels';
class VesselsComponent extends Component {
state = {
name: "",
imo: "",
editing: ""
};
componentWillMount() {
this.props.requestVessels();
}
toggleEditing(itemId) {
console.log("Editing" + ' ' + itemId);
this.setState({ editing: itemId });
}
handleVesselUpdate(vessel) {
this.props.updateVessel(vessel);
setTimeout(this.props.requestVessels, 600);
}
handleEditItem() {
let itemId = this.state.editing;
var editVessel = this.props.vessels.find((v) => v.Id === itemId);
editVessel.IMO = this.refs[`IMO_${itemId}`].value;
editVessel.AddedDate = this.refs[`AddedDate_${itemId}`].value;
editVessel.ModifiedDate = this.refs[`ModifiedDate_${itemId}`].value;
this.handleVesselUpdate(editVessel);
this.setState({ editing: "" });
}
renderItemOrEditField(vessel) {
if (this.state.editing === vessel.Id) {
return (
{vessel.Name}
{vessel.IMO}
)
} else {
return (
{vessel.Name}
{vessel.IMO}
);
}
}
renderVesselsTable(props) {
return (
Name |
IMO |
Actions |
{props.vessels.map(vessel =>
this.renderItemOrEditField(vessel)
)}
)
}
render() {
return (
Vessels
{this.renderVesselsTable(this.props)}
);
}
}
export default connect(
state => state.vessels,
dispatch => bindActionCreators(actionCreators, dispatch)
)(VesselsComponent);
Finally, here is the Vessel.js from the store.
const requestVesselsType = 'REQUEST_VESSELS';
const receiveVesselsType = 'RECEIVE_VESSELS';
const requestVesselType = 'REQUEST_VESSEL';
const receiveVesselType = 'RECEIVE_VESSEL';
const addVesselType = 'ADD_VESSEL';
const updateVesselType = "UPDATE_VESSEL";
const initialState = { vessels: [], vessel: {}, isLoading: false };
let currentvessel = {};
export const actionCreators = {
requestVessels: () => async (dispatch, getState) => {
dispatch({ type: requestVesselsType });
const url = 'api/VesselData/GetVessels';
const response = await fetch(url);
const allvessels = await response.json();
dispatch({ type: receiveVesselsType, allvessels });
},
requestVessel: () => async (dispatch, getState) => {
dispatch({ type: requestVesselType });
const url = 'api/VesselData/GetVessel/${id}';
const response = await fetch(url);
const vessel = await response.json();
dispatch({ type: receiveVesselType, vessel });
},
updateVessel: (vessel) => async (dispatch, getState) => {
const baseURL = "/api/VesselData";
const data = JSON.stringify({
Id: vessel.Id,
Name: vessel.Name,
IMO: vessel.IMO,
ModifiedDate: vessel.ModifiedDate,
AddedDate: vessel.AddedDate
});
const fetchTask = fetch(baseURL, {
method: "PUT",
headers: {
Accept: "application/json",
"Content-Type" : "application/json",
},
body: data
})
.then((data => {
dispatch({ type: updateVesselType, vessel: data })
}))
}
}
export const reducer = (state, action) => {
state = state || initialState;
if (action.type === requestVesselsType) {
return {
...state,
isLoading: true
};
}
if (action.type === receiveVesselsType) {
return {
...state,
vessels: action.allvessels,
isLoading: false
}
}
if (action.type === requestVesselType) {
return {
...state,
isLoading: true
};
}
if (action.type === receiveVesselType) {
currentvessel = action.vessel;
return {
...state,
vessel: currentvessel,
isLoading: false
}
}
if (action.type === updateVesselType) {
return {
...state,
isLoading: false
};
}
return state;
};
So, that's my application, it's basic and I'm still learning as I go but I can't see any logical reason for the lack of commit from the update method. The saving of the context is handled in the repository and I know it hits it and no record updates. Can anyone help me understand where I've gone wrong?
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)