My code is as follows:
const [ fields, setFields ] = useState({
fruit: 'default',
cheese: 'default',
})
const handleChange = (newFields) => setFields({...fields, ...newFields})
let a = new Fruit('fruit', fields, handleChange, 'What kind of fruit do you like?')
let b = new Cheese('cheese', fields, handleChange, 'What is your favorite cheese?')
return (
<div>
{a}
{b}
</div>
)
...
The classes Fruit and Cheese are defined as follows:
class Fruit {
constructor(name, fields, onChange, prompt) {
this.name = name
this.fields = fields
this.onChange = onChange
this.prompt = prompt
}
render() {
return (
<div>
{this.prompt}
<input
name={this.name}
value={this.fields[this.name]}
onChange={(e)=>this.onChange({
[this.name]: e.target.value
}) }
/>
</div>
)
}
}
The problem I'm having is that when the function this.onChange is called inside each class, it uses the value of fields that was set at the the constructor was called instead of the current value of fields. For example, if I enter 'apple' for fruit and then tried to enter 'cheddar' for cheese, the resultant fields will be {fruit: 'default', cheese: 'cheddar'}.
Is there a way to ensure that calling this.onChange will call the function outside the class (handleChange) which in turn will use the current copy of fields) ?