1

How can I set an array which I get from an api directly to a hook. The api returns a complete array not pieces.

If I do it this way:

  const [favorites, setFavorites] = useState(['']);

  const { data } = await axios.get(url, { headers });
  setFavorites(favorites => [...favorites, data.favorites]);

I get this output which is not correct:

(2) ["", Array(2)]
0: ""
1: (2) ["5ea42eae8750131824a5728f", "5ea5d29230778c1cd47e02dd"]
length: 2
__proto__: Array(0)

I do not want to have an array inside the array.

2 Answers 2

2

If data.favorites is an array as well you have to use spread in this case too.

setFavorites(favorites => [...favorites, ...data.favorites]);
Sign up to request clarification or add additional context in comments.

2 Comments

This seems to work but the first array entry is empty '', how can I prevent that?
It starts filling at array positon [1] not [0]
1

Have you tried this:

const [favorites, setFavorites] = useState(['']);

const { data } = await axios.get(url, { headers });
setFavorites(favorites => [...favorites, ...data.favorites]);

2 Comments

This seems to work but the first array entry is empty '', how can I prevent that?
It starts filling at array positon [1] not [0]

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.