I got this form where you can update user data (code, article, price, vat, status, companyid).
I would like to populate the Update/Edit form with user data so i can easly modify them (once this form shows up, i would like to get data from API in each input and show them as input value).
import { getUsers, editUser } from '../Service/api' import { useEffect } from 'react' const DialogEditUser = (data) => { const [RowData, SetRowData] = useState([]) const [ViewEdit, setEditShow] = useState(false) const [id, setId] = useState('') const [code, setCode] = useState('') const [article, setArticle] = useState('') const user = { id, code, article } const normalize = (v) => ({ code: String(v.code), article: String(v.article), }) const handleEditShow = () => { setEditShow(true) } const handleEditClose = () => { setEditShow(false) } const handleEdit = () => { editUser(data.props, normalize(user)) } useEffect(() => { getUsers() }, []) return ( <> <CButton style={{ marginRight: '10px', color: 'info', border: 'none', boxShadow: `2px 2px 9px -3px rgba(0,0,0,0.6)`, }} onClick={() => handleEditShow(SetRowData(data), setId(data.id))} > Edit </CButton> <CModal visible={ViewEdit} onClose={handleEditClose} backdrop={'static'} keyboard={false} portal={false} > <CModalHeader> <CModalTitle>Edit User:</CModalTitle> </CModalHeader> <CModalBody> <CForm> <CFormInput type="text" id="exampleFormControlInput1" label="Code :" placeholder="Enter Code" text=" " aria-describedby="exampleFormControlInputHelpInline" name="code" onChange={(e) => setCode(e.target.value)} defaultValue={RowData.code} /> <CFormInput type="text" id="exampleFormControlInput2" label="Article :" placeholder="Enter Article" text=" " aria-describedby="exampleFormControlInputHelpInline" name="article" onChange={(e) => setArticle(e.target.value)} defaultValue={RowData.article} /> <CModalFooter> <CButton color="secondary" onClick={() => setEditShow(false)}> Cancel </CButton> <CButton color="primary" onClick={() => { handleEdit() setEditShow(false) }} > Update </CButton> </CModalFooter> </CModal> </> ) } export default DialogEditUser
src/Service/api.js:
//... export const getUsers = async (id) => { id = id || '' try { return await axios.get(`${baseURL}`, config) } catch (error) { console.log('Error while calling getUsers api ', error) } } //...
Advertisement
Answer
Create a new function
that handle loading of data then created a useEffect
function and put inside the handled function so the data will be loaded in inputs
(populated):
useEffect(() => { loadArticleDetails() }, []) const loadArticleDetails = async () => { const response = await getUsers(id) console.log('Loading article details ', response) setArticleData(response.data.find((x) => x.id == data.props)) }
And in inputs, change each defaultValue to:
//... defaultValue={articleData.code} //Change code to its corresponding data: price, vat..etc //...