Reputation: 341
Currently I'm having a bit of trouble with changing an existing state.
const [selectedFormulas, setSelectedFormulas] = useState([]);
const searchForFormula = (event) => {
setSelectedFormulas((selectedFormulas) => {
return selectedFormulas.concat([event.target.value]);
});
}
What i want to achieve is that the selectedFormulas
becomes [selectedFormulas, event.target.value]
.
The event is out of scope inside the setState, but is there any way I can access the event, or achieve the result I want another way?
Upvotes: 0
Views: 692
Reputation: 2714
You don't need to define an arrow fnc here, it's just assign new value for selectedFormulas in fnc update state setSelectedFormulas()
const searchForFormula = (event) => {
const newValue = event.target.value;
setSelectedFormulas(selectedFormulas.concat([newValue]));
}
Upvotes: 1
Reputation: 175
const [selectedFormulas, setSelectedFormulas] = useState([]);
const searchForFormula = (event) => {
const {value} = event.target;
setSelectedFormulas([...selectedFormulas, value]);
}
Upvotes: 1
Reputation: 410
You can use event.persist();
const searchForFormula = (event) => { event.persist(); setSelectedFormulas((selectedFormulas) => { return selectedFormulas.concat([event.target.value]); }); }
Upvotes: 0
Reputation: 4869
Extract value out of the event and pass the variable
const searchForFormula = (event) => {
let value = event.target.value;
setSelectedFormulas((selectedFormulas) => {
return selectedFormulas.concat([value]);
});
}
Upvotes: 1