skip to Main Content

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


  1. 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:

    import { useEffect } from 'react'
    

    Then use it to issue a get request to the back end (with the other functions above your return statement):

    const getBook = async () => {
      try {
        return await axios.get("http://localhost:8001/books/" + bookId)
      } catch (err) {
        console.log('error! ',err)
      }
    }
    
    useEffect(() => {
      const currbook = getBook();
      // maybe you need to do something here to format the data
      setBook(currbook);
    }, [])
    

    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

      <input type="text" placeholder='title' onChange={handleChange} name='title' value={book.title} />
      <input type="text" placeholder='description' onChange={handleChange} name='description' value={book.description} />
      <input type="text" placeholder='cover' onChange={handleChange} name='cover' value={book.cover} />
      <input type="number" placeholder='price' onChange={handleChange} name='price' value={book.price} />
    
    Login or Signup to reply.
  2. All you have to do is connect each of the book’s keys with the input’s value properties.

    import { useState } from 'react'
    import { useParams } from 'react-router-dom'
    import axios from 'axios'
    
    const INITIAL_FORM = { // initialize a default form values
        title: '',
        description: '',
        cover: '',
        price: null,
    }
    
    const Update = () => {
        const [book, setBook] = useState(INITIAL_FORM)
        const { bookId } = useParams() // use :bookId param from router
    
        const handleChange = (e: any) => {
            setBook((prev) => ({ ...prev, [e.target.name]: e.target.value }))
        }
    
        const handleSubmit = async (e: any) => {
            e.preventDefault()
            try {
                const request = await axios.put('http://localhost:8001/books/' + bookId, book)
    
                if (![200, 201].includes(request.status)) return
    
                // handle after success...
                // e.g. navigate to somewhere else...
            } catch (err) {
                // handle error
            }
        }
    
        useEffect(() => {
            // get the initial book data from the server using the bookId
            const fetchData = async () => {
                try {
                    const { data } = await axios.get('http://localhost:8001/books/' + bookId)
                    setBook(data)
                } catch (err) {
                    // handle error
                }
            }
    
            fetchData()
        }, [])
    
        return (
            <div className="form">
                <h1>Update book</h1>
                <input
                    type="text"
                    placeholder="title"
                    value={book.title} // book's title
                    onChange={handleChange}
                    name="title"
                />
                <input
                    type="text"
                    placeholder="description"
                    value={book.description} // book's description
                    onChange={handleChange}
                    name="description"
                />
                <input
                    type="text"
                    placeholder="cover"
                    value={book.cover} // book's cover
                    onChange={handleChange}
                    name="cover"
                />
                <input
                    type="number"
                    placeholder="price"
                    value={book.price || ''} // book's price
                    onChange={handleChange}
                    name="price"
                />
                <button
                    className="formButton"
                    onClick={handleSubmit}
                >
                    Update book
                </button>
            </div>
        )
    }
    
    export default Update
    

    Additionally:

    • You could use react’s useParams() to get the bookId from the URL by implementing this in the router:
    {
       path: '/book-form-update/:bookId',
       element: <Update />,
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search