DeveloperRuwaid
DeveloperRuwaid

Reputation: 135

Update array with elements from another array react

I'm trying to update my array with elements from another array using useState Hook. Is there anyway to do it? thanks code --->


function App() {

  const nums = [1, 2, 3, 4, 5]
  const [numbers, setNumbers] = useState([])

  useEffect(() => {
    console.log(numbers)
    nums.forEach(num => {
      numbers.push(num);
    })
    setNumbers(numbers)
    console.log(numbers)
  }, [])


  return (
    <>
      {numbers.length && numbers.map(num => 
        <p key={Math.random() * 10000}>{num}</p>  
      )}
    </>
  );
}
export default App;

Upvotes: 0

Views: 501

Answers (2)

Sanish Joseph
Sanish Joseph

Reputation: 2256

I think you are trying to set nums in numbers. That can be easily done with const [numbers, setNumbers] = useState(nums). I just initialized numbers with nums. You don't event need a useEffect.

If you really want to experiment with useEffect then don't mutate the data with push. You can use filter, map and reduce to deal with arrays to avoid mutation. Or just use the spread syntax like another answer posted.

setNumbers([...nums]);

Upvotes: 0

Stefanie Gauss
Stefanie Gauss

Reputation: 737

I assume what you mean is, you want to make a copy of that array, as your own data, so you can just do:

  useEffect(() => {
    setNumbers([...nums]);
  }, []);

or you can even do

const [numbers, setNumbers] = useState([...nums]);

without the useEffect().

You can use

const [numbers, setNumbers] = useState(nums);

but just note that numbers and nums refer to the same array object this way.

By the way, using a random number as the key defeats the purpose of it... but you may already know that.

Upvotes: 1

Related Questions