Reputation: 404
I have an axios request for getting details of a transaction
getTransaction(batchRef) {
return axios.post(`${API_BASE_URL_GET_OUTWARD_TRANSACTION}`, {
batchRef: batchRef,
});
}
And I call it through this service:
const [viewOutward, setViewOutward] = useState([]);
OutwardService.getTransaction(rowData.batchRef).then((response) => {
setViewOutward(response.data);
});
It is correctly being set as a json on viewOutward state like this e.g. {reference: "2020091600", relatedReference: "2020091601}
Now, I want to assign these values directly onto textfields
I'm doing it this way and I'm not sure whether it is a good practice to use map on every field.
<TextField
variant="outlined"
margin="normal"
required
autoComplete="off"
fullWidth
type="text"
id="reference"
label="Reference"
value={viewOutward.map((viewOutward) => viewOutward.reference)}
onChange={(e) => setViewOutward(e.target.value)}
InputProps={{
classes: { input: classes.textfield1 },
}}
inputProps={{
maxLength: 16,
}}
/>
It is working however it could take a toll on the perfomance?
Can someone suggest the proper way of setting these values on the textfields using only one state. Thank you.
Upvotes: 0
Views: 363
Reputation: 478
[{reference: "2020091600", relatedReference: "2020091601"}, {reference: "2020091602", relatedReference: "2020091602"}, ...]
viewOutward.map((item, index) =>
<TextField
variant="outlined"
margin = "normal"
required
autoComplete = "off"
fullWidth
type = "text"
id = `${item.reference}` // if reference is unique
label = "Reference"
key = { index } // to identity unique for react
value = { item.reference } // assign value
onChange = {(e) => //onchange of text assign new value to same object
setViewOutward(vo =>
vo.map(row => row.reference === item.reference
? { ...row, reference: e.target.value //whatever property you can update
} : row)
)
}
InputProps = {{
classes: { input: classes.textfield1 },
}}
inputProps = {{
maxLength: 16,
}}
/>
)
Adding Reference for how to update state of an array of object
Upvotes: 2