Click here to Skip to main content
15,389,584 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hello community I want to edit my data which comes from API and display in input field in React JS.

JavaScript
      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 (
    <input type="text" name="name" autoComplete='off' placeholder='Enter Name' value={userData.myObject.name} onChange={inputHandler}/>
  );
}


What I have tried:

I want to edit my input field value and update and save in database. Thanks in advance.
Posted
Updated 1-Apr-22 0:21am
Comments
Richard Deeming 30-Mar-22 9:25am
   
You forgot to ask a question.

Click the green "Improve question" link and update your question with a clear description of what you are trying to do, what you have tried, and where you are stuck.

Include the full details of any errors.

1 solution

Your state is:

{myObject: {
   name: '',
   email: ''
}}


But you have not updated the value for MyObject.name in inputHandler. First, you need to create value in your first object.
Hence, the outcome will be:

{MyObject:{
   name:'',
   email:''
 },
 name:yorurInputValue
}


Now execute this:
useState({
  name:'',
  email:''
})


Hope this should work!
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900