#Rendering saved data on edit form in CRUD app

13 messages · Page 1 of 1 (latest)

broken relic
#

Hello, everyone!

I am a beginner and this is my first time making a CRUD app, so this is probably very embarrassing. I am nearly done, but really struggling to get the currently saved data to fill the input fields on my edit page. I have been looking at videos and articles since yesterday, but sadly only getting more confused. I am now getting the data in my console, but having trouble figuring out how to get it on the page. I would really appreciate if someone can point me in the right direction. Let me know if there's any way I can make helping me out easier for you all.

My full edit file:

import axios from 'axios';
import React, { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';

const EditHospital = () => {
    const navigate = useNavigate();
    const location = useLocation();

    // Gets the id for the entry being edited from the endpoint
    const hospitalId = location.pathname.split('/')[2];

    // const [input, setInput] = useState([]);

    useEffect(() => {
        const getInputs = async () => {
            try {
                const res = await axios.get(
                    'http://localhost:4000/hospitals/' + hospitalId
                );
                // setInput(res.data);
                console.log(res.data);
            } catch (err) {
                console.log(err);
            }
        };

        getInputs();
    }, []);

    const [input, setInput] = useState({
        name: '',
        location: '',
        type: '',
        phone: '',
    });

    const handleChange = (event) => {
        setInput((prev) => ({
            ...prev,
            [event.target.name]: event.target.value,
        }));
    };

    const handleClick = async (event) => {
        event.preventDefault();
        try {
            await axios.put(
                'http://localhost:4000/hospitals/' + hospitalId,
                input
            );
            navigate('/');
        } catch (err) {
            console.log('Unable to process update.');
        }
    };

    return (
        <div className='form'>
            <h1>Edit Hospital Details</h1>
            <input
                type='text'
                placeholder='name'
                onChange={handleChange}
                name='name'
            />
            <input
                type='text'
                placeholder='location'
                onChange={handleChange}
                name='location'
            />
            <select
                onChange={handleChange}
                className='hospital-type-dropdown'
                name='type'
            >
                <option value='general'>General</option>
                <option value='pediatric'>Pediatric</option>
                <option value='cardiology'>Cardiology</option>
                <option value='neurology'>Neurology</option>
                <option value='orthopedic'>Orthopedic</option>
            </select>
            <input
                type='text'
                placeholder='phone'
                onChange={handleChange}
                name='phone'
            />
            <button className='form-button' onClick={handleClick}>
                Save
            </button>
        </div>
    );
};

export default EditHospital;

And, again, I am finally getting the data through when accessing my edit page in my console- but in case it is helpful, here is my get request in the backend:

app.get('/hospitals/:id', (req, res) => {
    const hospitalId = req.params.id;
    const q = 'SELECT * FROM `hospitals` WHERE id = ?';

    db.query(q, [hospitalId], (err, data) => {
        if (err) {
            return res.json(err);
        } else {
            return res.json(data);
        }
    });
});

I apologize for such a long post. I hope someone can point me in the right direction. I would be eternally grateful! Thank you all.

viral summit
#

I think you would set the fetched input to input by using setInput and they you can have value attribute in the input tag to display the fetched data. Like input type='text' placeholder='name' onChange={handleChange} name='name' value = {input.name} />

broken relic
#

Thank you so much for the reply!

I did try to do that, but I got this warning in the console, and my value did not come through:

index.js:1210 Warning: A component is changing a controlled input to be uncontrolled. This is likely caused by the value changing from a defined to undefined, which should not happen. Decide between using a controlled or uncontrolled input element for the lifetime of the component.
#

That was with me uncommenting setInput(res.data) in my getInputs function. Do I need to set my inputs a different way?

viral summit
#

Can I see all of your updated code?

#

actually, it would be better if you make code sandbox

broken relic
#

Ok, let me get that going right now! I really, really appreciate you taking a look.

viral summit
#

👍

broken relic
#

Sorry, I am working on it- Getting some authorization problem.

#

Okay, for some reason I'm having some issues getting it up on CodeSandbox. : ( Found someone IRL to help me take a look though, so no need to wait around for me. I really appreciate you taking a look when you did. Do I need to close this post somehow?

Thanks again!

viral summit
#

No worries. You can close the channel by using the /close command

broken relic
#

Awesome. Thanks so much!