Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I can't seem to push an object to array in state from an API. This is my code

      async _fetchData(number){
        try{
          await console.log('asd',number)
          let response = await fetch( 'https://www.beanlinked.com/wp-json/wp/v2/media/'+this.state.News[number].featured_media)
          let responseJson = await response.json()
          await console.log("responseJson")
          let tempURL = responseJson.guid
          let url = tempURL.rendered

          for (var i = 0; i < this.state.News.length; i++) {
            const items = this.state.News;
            items[number].URLOnSever = url;

          }

          this.state.News.push({
            URLOnSever : url
          })
          console.log("imageurl",this.state.News.URLOnSever)

          return url
        }catch(e){
          console.log('problem'+e)
        }
      }

I just want to push the new URL to this.state.News.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
138 views
Welcome To Ask or Share your Answers For Others

1 Answer

Don't mutate state, which you are doing with Array#push -- mutating an array inside state. Use setState instead to create a new array with the old array plus added elements set into state instead of pushing to the old one:

this.setState(prevState => ({
  News: [
    ...prevState.News,
    { URLOnServer: url }
 ]
}));

This will set News to the previous state's News array contents (via array spread syntax) plus the new object. It's the same as your code, but without mutation of state directly. Learn more at the React documentation.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...