I am build a form that is pre-populated by the results of an axios get request to a node API that returns an array (stored in MySQL).
I can get the data to map onto the form, but i cannot edit the form. The idea is for it to be an "edit user" form. I suspect the issue is in the onChange portion of the input field.
The form is accessed from a table that is also mapped with the results of a get request. Upon clicking the edit button, the userID from the table row is passed to the edit form through useNavigate and useLocation (I can add this portion of code if needed).
Here is the portion of code that performs the request to the API:
useEffect(() => {
const config = {
headers: { "x-auth-token": token },
};
const fetchData = async () => {
const results = await api.get("/users/edituser/" userID, config);
setRows(results.data);
};
fetchData();
}, [setRows, userID, token]);
State for "rows" (set on API response):
const [rows, setRows] = useState([]);
And finally, an example input field:
<input
type="text"
className="form-control"
id="inputEmail4"
placeholder="First Name"
name="firstName"
value={rows.firstName}
onChange={(e) => setFirstName(e.target.value)}
></input>
I would greatly appreciate any assistance with this. Let me know if I can supply any more code.
CodePudding user response:
You cannot do value={rows.firstName}
since rows
is an array. Based on the name of your API endpoint ("/users/edituser/" userID
), I'm inferring that rows
will only contain one person object inside of it.
In that case you would destructure rows
to access the user
object:
const [user] = rows;
<input value={user.firstName} />
Alternatively, you could have your API return an object instead of an array and keep what you currently have, and just change the rows
array to a user
object in your React code.