I am trying to update Book in Update page, and am not sure how to use old values instead of all inputs being cleared, and am not sure where to look at for it. Below is my form in Update page
return (
<div className='form'>
<h1>Update book</h1>
<input type="text" placeholder='title' onChange={handleChange} name='title'></input>
<input type="text" placeholder='description' onChange={handleChange} name='description'></input>
<input type="text" placeholder='cover' onChange={handleChange} name='cover'></input>
<input type="number" placeholder='price' onChange={handleChange} name='price'></input>
<button className="formButton" onClick={handleClick}>Update book</button>
</div>
and other things in class like hook UseState() which uses all empty values (am not sure if i should and how to populate with old values)
import React from 'react'
import {useState} from 'react'
import axios from 'axios'
import { useNavigate,useLocation } from 'react-router-dom'
const Update = () => {
const[book,setBook]=useState({
title:"",
description:"",
cover:"",
price: null
})
const navigate = useNavigate();
const location=useLocation()
const bookId=location.pathname.split("/")[2]
const handleChange =(e)=>{
setBook(prev=>({...prev, [e.target.name]:e.target.value}))
console.log(e.target.name)
}
const handleClick = async e =>{
e.preventDefault()
try{
await axios.put("http://localhost:8001/books/"+bookId,book)
navigate("/")
console.log(book.title)
}catch(err){
In the form for updating i have placed key={book.ID} and then tried to use value {book.title},{book.description} etc., but nothing is showing. Would be very grateful if someone knows how that can be fixed.Thank you for reading.(i am trying to have inputs filled with old values instead of being empty)
2
Answers
You need to do something to get the book data initially and use it to set the book state. This is not tested because I don’t have access to the back end you are using, but something like this.
Add the useEffect hook to your imports:
Then use it to issue a get request to the back end (with the other functions above your return statement):
The [] as the second parameter to the useEffect hook means this will only run once after the initial render.
Then don’t forget to put the resulting values of the book into your JSX
All you have to do is connect each of the book’s keys with the input’s value properties.
Additionally:
useParams()
to get thebookId
from the URL by implementing this in the router: