user13262487
user13262487

Reputation: 209

React hook set array from api directly to state

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.

Upvotes: 1

Views: 134

Answers (2)

gqstav
gqstav

Reputation: 2082

Have you tried this:

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

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

Upvotes: 1

Mark  Partola
Mark Partola

Reputation: 674

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

setFavorites(favorites => [...favorites, ...data.favorites]);

Upvotes: 2

Related Questions