Home > OS >  how to access a variable outside onClick function react
how to access a variable outside onClick function react

Time:10-17

I'm trying to get list from the onClick function but I can't if there any solution, please. here is my full code link

let abe = []
const click = (e) => {
    const cityy = e.target.value
    const checkUsername = obj => obj.city === cityy;
    const result = abe.some(checkUsername)

    if (!result) {
        abe.push({ "city": cityy})
    }

    if (!e.target.checked) {
        const indexe = abe.findIndex(p => p.city === cityy)
        abe.splice(indexe, 1)
    }

    const simo = watch("simo")
    let list = abe.map((list) => list.city).join(" , ")
}

CodePudding user response:

Is the click function triggered in the first place? You have actually missed to show where the click function is used.

Here is an example. Looks like you have to store cities in the state.

const [citiesList, setCitiesList] = useState<string[]>([]);


const click = (e) => {
    const cityy = e.target.value
    const checkUsername = obj => obj.city === cityy;
    const result = citiesList.some(checkUsername)

    if (!result) {
        setCitiesList(prevState => [...prevState, cityy]);
     
    }

    if (!e.target.checked) {
        const cList = [...citiesList];
        const indexe = cList.findIndex(p => p === cityy)
        cList.splice(indexe, 1);
        setCitiesList(cList);
    }

    const simo = watch("simo");
}
  • Related