Danoctum
Danoctum

Reputation: 341

React access out-of-scope variable in setState

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

Answers (4)

SanjiMika
SanjiMika

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

C Ankita
C Ankita

Reputation: 175


    const [selectedFormulas, setSelectedFormulas] = useState([]);

    const searchForFormula = (event) => {
    const {value} = event.target;
        setSelectedFormulas([...selectedFormulas, value]);
    }

Upvotes: 1

Ashish
Ashish

Reputation: 410

You can use event.persist();

const searchForFormula = (event) => { event.persist(); setSelectedFormulas((selectedFormulas) => { return selectedFormulas.concat([event.target.value]); }); }

Upvotes: 0

kooskoos
kooskoos

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

Related Questions