0

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;

1
  • 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. Commented Sep 23, 2021 at 18:50

2 Answers 2

1

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.

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

Comments

0

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]);

2 Comments

Spread syntax works perfectly..but I actually need to use useEffect as I'm fetching data from an api. And that's an array of objects..and I want to update my state with an array containing the objects.....
this is the actual code ``` useEffect(() => { let getProducts: () => Promise<void> getProducts = async () => { const res = await commerce.products.list(); res.data.forEach((product) => { products.push( { name: product.name, description: product.description, price: product.price.formatted_with_symbol, id: product.id, imgURL: product.media.source } ) }) setProducts([...products]); } getProducts(); }, []) ```

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.