1

i want to Update an empty array by another array, i cant realy figure out how todo that,

const [avatar, setAvatar] = useState([]);

and i want to update the empty array with another array like this:

PlayerService.getAvatars()
                    .then(response => {
                        setAvatar(avatar => [...avatar, response])
                    })

the problem here is, that the 4 items i get from the response , they will be set to the first element of the avatar array, not to multiple,

that means, i get under avatar[0] , all the items together, they dont split up like they should.

i hope you can follow me, im not a native english speaker

1
  • try setAvatar(response) if response is an array Commented Jun 5, 2020 at 10:05

1 Answer 1

2

you can concat array if you want to combine two array like this .

PlayerService.getAvatars()
    .then(response => {
        let arr1 = avtar;
        let arr2 = response;
        let arr3 = arr1.concat(arr2);
        setAvatar(arr3)
    })
Sign up to request clarification or add additional context in comments.

3 Comments

thats very weird, in arr3 are all elements, but if i do setAvatar and then console.log it , it is still empty then .. o.O
this is the async operation . console it before return and check again .
Ahh perfect, i didnt know that it is async ... , so at the end i can do setAvatar(response) , but thanks for all the Info, it helpt me to fix my problem

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.