I have an edit for that use to work perfectly unit someone on the team reconfigured that data payload for the API, now having a nested entity called "data". Here is what the new returning payload looks like:
{
"status": 1,
"data": {
"name": "Tank 101",
"dimensions": "76.0 x 90.5 x 101.0",
}
}
Originally before the entities were nested inside if a data entity I would just call to values.name and values.dimensions on my Details and Edit pages to access the values. After the data reconfiguration, I updated to values.data.name and values.data.dimensions. This worked perfectly for my details page and to populate the existing values for my edit page, but my edit page throws this error on the code I use to disable my submit:
Uncaught TypeError: Cannot read properties of undefined (reading ‘name’)
The line of code throwing the error is:
const disabled = (!values.data.name || !values.data.dimensions );
Which I use to disable the submit button id the value is undefined or null.
Here is my Form:
const [values, setValues] = React.useState({} as any);
React.useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const res = await axios.get(`${detailsUrl + selectedRecord.id}`);
setValues( res.data );
} catch (error) {
setValues( error.response.data );
}
setLoading(false);
};
fetchData();
}, []);
// Conditions to disable submit button
const disabled = (!values.data.name || !values.data.dimensions );
// Form
return
<>
{values.status !== 1 ? <DataError /> :
<Form onSubmit={handleSubmit} >
<Controls.Input
type='text'
onChange={handleInputChange}
name='name'
label='Equipment Name'
value={values.data.name}
/>
<Controls.Input
type='text'
onChange={handleInputChange}
name='dimensions'
label='Equipment Dimensions'
value={values.data.dimensions}
/>
<Button
type='submit'
text='Submit'
onClick={handleSubmit}
disabled={disabled}
/>
</Form>
}
</>
);
2
Answers
change
setValues( res.data )
tosetValues( res )
or
to
Since you’re using
React.useState
to initialize values with an empty object({})
, the data property inside values is initiallyundefined
, which is causing the error when you try to accessvalues.data.name
andvalues.data.dimensions
in the initial render.You can either set the initial state of values with the required structure, including the
data
property, or just add a check before accessing the nested properties