0

I am using prev state to append the array and I need to set the whole array to an empty array on the button clicked. I tried using setArray({}) but it doesn't work. how to completely set the array to an empty array on button click

import React, {useState,useEffect} from 'react'

function testFunction() {

    const [features, setFeatures] = useState({});

    const add = (key,value) => {
        setFeatures((prevFeatures)=>({...prevFeatures,[key]: value}));
    }

    const clear =() =>{
        setFeatures({});
    }

    return (
        <div>
            
            <div>
                <select onChange={(event)=>add(event.target.name,event.target.value)}>
                    <option name="opt1" value="val1">Value1</option>
                    <option name="opt2" value="val2">Value2</option>
                    <option name="opt3" value="val3">Value3</option>
                    <option name="opt4" value="val4">Value4</option>
                    <option name="opt5" value="val5">Value5</option>
                </select>
            </div>

            <button type="reset" value="reset" onClick={()=>clear}>Reset</button>

        </div>
    )
}
export default testFunction

4
  • 1
    where is the features state? Commented Mar 31, 2021 at 15:39
  • There's no feacture state and probably prevFeatures is undefined too. You should have something like const [feature, setFeature] = useState([]); and whenever you want to set that feature state to an empty array do something like setFeature([]). The code is unclear atm tho. Commented Mar 31, 2021 at 15:41
  • @İlker a small mistake was there. now updated Commented Mar 31, 2021 at 16:40
  • @EdgardoRodríguez a small mistake was there. now updated Commented Mar 31, 2021 at 16:40

2 Answers 2

2

First of all you didn't initialize your state as an array? So first let's do that;

const [features, setFeatures] = useState([])

also your functions should be like this;

 const add = (key,value) => {
        setFeatures((prevFeatures)=>([...prevFeatures, {[key]: value} ])); // key, value added to array of Objects
    }

    const clear =() =>{
        setFeatures([]); // setting empty array
    } 

also you should call clear function ;

<button type="reset" value="reset" onClick={()=>clear()}>Reset</button>

Sign up to request clarification or add additional context in comments.

1 Comment

@NathinduDias well I'm updating the answer
1

You must execute your function clear because in your code you are only passing the declared function.

<button type="reset" value="reset" onClick={()=>clear}>Reset</button>

onClick={()=>clear} must be replaced for onClick={()=>clear()} or onClick={clear}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.