React JS - How to edit input field API data in React JS?

Hello community I want to edit my data which comes from API and display in input field in React JS.

const UserInfo = () => {

        const [userData,setUserData] = useState({myObject: {
           name: '',
           email: ''
       }});
       const {id} = useParams();
       useEffect(()=>{
          axios.get(`http://localhost:8080/users/user-info/${id}`)
          .then(res =>{
          const getData = res.data.data;
          setUserData({myObject : getData});
       }).catch(e => console.log(e));
      },[]);

      const inputHandler = (e) =>{
          setUserData(userData =>({...userData, [e.target.name] : e.target.value}))
      }

     return (
         <>
               //JSX Code//
                <input type="text" name="name" autoComplete='off' placeholder='Enter Name' value={userData.myObject.name} onChange={inputHandler}/>
               //JSX Code//

        </>
     );
   }

I want to edit my input field value and update and save in database. Thanks in advance.

Hi,

What have you tried and what is not working?

The code you have posted seems to pull a specific user from the DB, populate an input field with their values and then keep track of those values in state.

FWIW, this doesn’t look right to me:

const [userData, setUserData] = useState({
 myObject: {
   name: '',
   email: '',
 },
});

and:

setUserData((userData) => ({
  ...userData,
  [e.target.name]: e.target.value,
}));

But as mentioned, it would be better to get some more information about what is not working.

1 Like