1

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?

1
  • It doesn't work because you use setAllValues where your function name is setValue Commented Apr 14, 2020 at 6:59

2 Answers 2

3

Use the functional form of setState:

 setAllValues(prevValue => [...prevValue, newValue])
Sign up to request clarification or add additional context in comments.

Comments

1

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('');
}

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.