I am learning about react and I have come across a scenario in which the behaviour is not what I expected.
I have a react funcional component like so:
import { Box, Button, Grid, ThemeProvider, createTheme } from '@mui/material';
import './styling/App.css';
import RawPayloadUI from './components/RawPayloadUI';
import FormUI from './components/FormUI';
import { useState } from 'react';
import { Template } from './TemplateExporter';
function App() {
const testFormFields = {...Template};
const [currentUI, setCurrentUI] = useState('rawPayloadUI');
const [formFields, setFormFields] = useState(testFormFields);
const userInterfaces = ['rawPayloadUI', 'formUI'];
const uiButtonHandler = e => {
setFormFields(Template);
//console.log(formFields);
setCurrentUI(e.currentTarget.value)
}
return (
<ThemeProvider theme={theme}>
<div className="App">
<div className='App-header'></div>
<Grid id='Form' container sx={{ flexDirection: 'row', height: 'fit-content', marginTop: '1vh', justifyContent: 'center' }} spacing={2}>
{userInterfaces.map((userInterface, idx) => {
return (
<Grid item key={idx}>
<Button value={userInterface} onClick={uiButtonHandler}>{userInterface}</Button>
</Grid>
)
})}
</Grid>
{currentUI === 'formUI' && <FormUI onChange={setFormFields} formFields={formFields} />}
{currentUI === 'rawPayloadUI' && <RawPayloadUI />}
</div>
</ThemeProvider>
);
}
export default App;
I am trying to reset the formFields
state back to the default value when the user switches to a different interface via the uiButtonHandler()
method. But it seems like the values set by the onChange
method of the FormUI
component are being persisted which indicates to me that the underlying base object (Template
) is being mutated.
Im not sure what part of the code is causing this mutation.
Can anyone explain which part of the code is causing the data from the onChange
method to interact with the Template
.