Asking
Asking

Reputation: 4172

Add multiple value in array

In my application, in React i have next situation: I have input where i add different values when i click on save. The value from input is converted from string to array. So, first time i added a text, i clicked save, and i have 1 value in array. Second time, i add another text, i click, on save and the first value is changed by second. I store value in this state:

const [value, setValue] = useState([here comes my value]);

I want to concat the value one after one and i did:

useEffect(()=> {
    setAllValues([...value, value])
  }, [value])

..but this does't work. How to store all values in one array?

Upvotes: 1

Views: 58

Answers (2)

Pushkin
Pushkin

Reputation: 3604

To perform that operation you would need two states

// one state for array
const [valueArray, setValueArray] = useState([here comes my value]);

// and another state for string
const [value, setValue] = useState('');


// then onSave function
const onSave = () => {
  setValueArray([  ...valueArray, value ]);
  setValue('');
}

Upvotes: 1

Clarity
Clarity

Reputation: 10873

Use the functional form of setState:

 setAllValues(prevValue => [...prevValue, newValue])

Upvotes: 3

Related Questions