Im trying to pass an Id (could be seen as a state i guess) from a component to another
In component Home:
interface FetchDataExampleState {
games: Games[];
loading: boolean;
}
interface Games {
g_Id: number;
g_Title: string;
g_Genre: string;
g_Plattform: string;
g_ReleaseDate: Date;
g_Price: number;
}
i got the 2 Interfaces from which i want to pass the g_Id to use in in EditGame
My Put API:
[HttpPut("{id}")]
[Route("EditGame")]
public async Task<IActionResult> PutGame([FromRoute] int id, [FromBody] Game game)
{
game.G_Id = id;
_context.Entry(game).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!GameExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
The fetch im Trying to use in the EditGame component :
handleClick = (e: any) => {
console.log("Hello");
fetch("api/Games/EditGame", {
method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({
g_Title: this.state.g_Title,
g_Genre: this.state.g_Genre,
g_Plattform: this.state.g_Plattform,
g_ReleaseDate: this.state.g_ReleaseDate,
g_Price: this.state.g_Price,
})
})
.then(response => response.json())
.then(data => {
console.log(data)
this.setState({
g_Title: data.g_Title,
g_Genre: data.g_Genre,
g_Plattform: data.g_Plattform,
g_ReleaseDate: data.g_ReleaseDate,
g_Price: data.g_Price,
});
let path = '/Home';
this.props.history.push(path);
});
}
My Routes :
<Route path='/Home' component={Home} />
<Route path='/EditGame' component={EditGame} />
I tried looking it up and tried all the Top results including:
I'm not sure if im missing something since i'm new to react or if i'm doing something wrong. Thanks for the Help :)
So after a long time of searching i was able to solve it as following
<li><Link to={{ pathname: "/EditGame", state: { id: games.g_Id, title: games.g_Title, genre: games.g_Genre, Plattform: games.g_Plattform, rdate: games.g_ReleaseDate, price: games.g_Price } }} >Edit</Link></li>
by calling the values from home and passing them through state to EditGame where i called them like this in the fitch method
handleClick = (e: any) => {
console.log("Hello");
fetch("api/Games/EditGame", {
method: 'PUT' + this.props.location.state.id, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({
g_Id: this.props.location.state.id,
g_Title: this.props.location.state.title,
g_Genre: this.props.location.state.genre,
g_Plattform: this.props.location.state.Plattform,
g_ReleaseDate: this.props.location.state.rdate,
g_Price: this.props.location.state.price,
})
})
.then(response => response.json())
.then(data => {
console.log(data)
this.setState({
g_Title: data.g_Title,
g_Genre: data.g_Genre,
g_Plattform: data.g_Plattform,
g_ReleaseDate: data.g_ReleaseDate,
g_Price: data.g_Price,
});
let path = '/Home';
this.props.history.push(path);
});
}
now it might not be the best way, but it works just fine.