setState of many items React












0














I am trying to build a news app that displays top 20 articles per country. However, I tried putting my setState call inside a loop but I quickly realized that they were being overwritten and the only one that would display is the last one. I was wondering how could I achieve this without overriding the previous entries. Thank you in advance!



//the following code is inside my App.js file and inside the App component
getNews = async (e) => {
e.preventDefault();
const country = e.target.elements.country.value;
const api_call = await fetch(this.buildURL(country));
const data = await api_call.json();

if (country) {
console.log(data);

//i changed this to just display the first article out of 20
this.setState({
title: data.articles[0].title,
image: data.articles[0].urlToImage,
description: data.articles[0].description,
author: data.articles[0].author,
link: data.articles[0].url,
err: ""
});
}
else {
this.setState({
title: undefined,
image: undefined,
description: undefined,
author: undefined,
link: undefined,
err: "Please enter valid country"
});
}


}

render() {
return(
<div>
<Titles />
<Form getNews={this.getNews}/>
<News title={this.state.title}
image={this.state.image}
description={this.state.description}
author={this.state.author}
link={this.state.link}
err={this.state.err}
/>
</div>
);
}


This is a beginners project so pls keep that in mind haha.










share|improve this question






















  • What kind of response do you get from your API? can you edit the question so we can understand better?
    – Akar
    Nov 22 at 19:58










  • Also, having a bit more of your app code helps. From the looks of it though I do not see anything looping over your response data to store articles, nor do I see in the render function some array map function to render the resultant array of articles.
    – Drew Reese
    Nov 22 at 20:12


















0














I am trying to build a news app that displays top 20 articles per country. However, I tried putting my setState call inside a loop but I quickly realized that they were being overwritten and the only one that would display is the last one. I was wondering how could I achieve this without overriding the previous entries. Thank you in advance!



//the following code is inside my App.js file and inside the App component
getNews = async (e) => {
e.preventDefault();
const country = e.target.elements.country.value;
const api_call = await fetch(this.buildURL(country));
const data = await api_call.json();

if (country) {
console.log(data);

//i changed this to just display the first article out of 20
this.setState({
title: data.articles[0].title,
image: data.articles[0].urlToImage,
description: data.articles[0].description,
author: data.articles[0].author,
link: data.articles[0].url,
err: ""
});
}
else {
this.setState({
title: undefined,
image: undefined,
description: undefined,
author: undefined,
link: undefined,
err: "Please enter valid country"
});
}


}

render() {
return(
<div>
<Titles />
<Form getNews={this.getNews}/>
<News title={this.state.title}
image={this.state.image}
description={this.state.description}
author={this.state.author}
link={this.state.link}
err={this.state.err}
/>
</div>
);
}


This is a beginners project so pls keep that in mind haha.










share|improve this question






















  • What kind of response do you get from your API? can you edit the question so we can understand better?
    – Akar
    Nov 22 at 19:58










  • Also, having a bit more of your app code helps. From the looks of it though I do not see anything looping over your response data to store articles, nor do I see in the render function some array map function to render the resultant array of articles.
    – Drew Reese
    Nov 22 at 20:12
















0












0








0


1





I am trying to build a news app that displays top 20 articles per country. However, I tried putting my setState call inside a loop but I quickly realized that they were being overwritten and the only one that would display is the last one. I was wondering how could I achieve this without overriding the previous entries. Thank you in advance!



//the following code is inside my App.js file and inside the App component
getNews = async (e) => {
e.preventDefault();
const country = e.target.elements.country.value;
const api_call = await fetch(this.buildURL(country));
const data = await api_call.json();

if (country) {
console.log(data);

//i changed this to just display the first article out of 20
this.setState({
title: data.articles[0].title,
image: data.articles[0].urlToImage,
description: data.articles[0].description,
author: data.articles[0].author,
link: data.articles[0].url,
err: ""
});
}
else {
this.setState({
title: undefined,
image: undefined,
description: undefined,
author: undefined,
link: undefined,
err: "Please enter valid country"
});
}


}

render() {
return(
<div>
<Titles />
<Form getNews={this.getNews}/>
<News title={this.state.title}
image={this.state.image}
description={this.state.description}
author={this.state.author}
link={this.state.link}
err={this.state.err}
/>
</div>
);
}


This is a beginners project so pls keep that in mind haha.










share|improve this question













I am trying to build a news app that displays top 20 articles per country. However, I tried putting my setState call inside a loop but I quickly realized that they were being overwritten and the only one that would display is the last one. I was wondering how could I achieve this without overriding the previous entries. Thank you in advance!



//the following code is inside my App.js file and inside the App component
getNews = async (e) => {
e.preventDefault();
const country = e.target.elements.country.value;
const api_call = await fetch(this.buildURL(country));
const data = await api_call.json();

if (country) {
console.log(data);

//i changed this to just display the first article out of 20
this.setState({
title: data.articles[0].title,
image: data.articles[0].urlToImage,
description: data.articles[0].description,
author: data.articles[0].author,
link: data.articles[0].url,
err: ""
});
}
else {
this.setState({
title: undefined,
image: undefined,
description: undefined,
author: undefined,
link: undefined,
err: "Please enter valid country"
});
}


}

render() {
return(
<div>
<Titles />
<Form getNews={this.getNews}/>
<News title={this.state.title}
image={this.state.image}
description={this.state.description}
author={this.state.author}
link={this.state.link}
err={this.state.err}
/>
</div>
);
}


This is a beginners project so pls keep that in mind haha.







javascript arrays json setstate






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 22 at 19:54









lcch

31




31












  • What kind of response do you get from your API? can you edit the question so we can understand better?
    – Akar
    Nov 22 at 19:58










  • Also, having a bit more of your app code helps. From the looks of it though I do not see anything looping over your response data to store articles, nor do I see in the render function some array map function to render the resultant array of articles.
    – Drew Reese
    Nov 22 at 20:12




















  • What kind of response do you get from your API? can you edit the question so we can understand better?
    – Akar
    Nov 22 at 19:58










  • Also, having a bit more of your app code helps. From the looks of it though I do not see anything looping over your response data to store articles, nor do I see in the render function some array map function to render the resultant array of articles.
    – Drew Reese
    Nov 22 at 20:12


















What kind of response do you get from your API? can you edit the question so we can understand better?
– Akar
Nov 22 at 19:58




What kind of response do you get from your API? can you edit the question so we can understand better?
– Akar
Nov 22 at 19:58












Also, having a bit more of your app code helps. From the looks of it though I do not see anything looping over your response data to store articles, nor do I see in the render function some array map function to render the resultant array of articles.
– Drew Reese
Nov 22 at 20:12






Also, having a bit more of your app code helps. From the looks of it though I do not see anything looping over your response data to store articles, nor do I see in the render function some array map function to render the resultant array of articles.
– Drew Reese
Nov 22 at 20:12














2 Answers
2






active

oldest

votes


















1














So you want include all news items in state, then loop over them and create a News element for each of them. Something like this for the request:



getNews = async e => {
e.preventDefault();
const country = e.target.elements.country.value;
if (!country) {
this.setState({
articles: null,
err: "Please enter valid country"
});
}
let data;
try {
data = await fetch(this.buildURL(country)).then(res => res.json());
} catch (error) {
this.setState({
articles: null,
err: "Please enter valid country"
});
}
if (data) {
this.setState({
articles: data.map(article => ({
title: article.title,
image: article.urlToImage,
description: article.description,
author: article.author,
link: article.url
}))
});
}
};


although I do not guarantee it is bug free!



Then when you have all articles in state, you can loop over them:



render() {
return (
<div>
<Titles />
<Form getNews={this.getNews} />

{this.state.articles.map(article => (
<News
title={article.title}
image={article.image}
description={this.state.description}
author={article.author}
link={article.link}
err={article.err}
/>
))}
</div>
);
}


or you can spread the props like this, if you know the object key names you stored in state match exactly those the News component expects:



  {this.state.articles.map(article => (
<News {...article}/>
))}





share|improve this answer





























    0














    Your state should have an array instead of just provision for one object.



    this.setState({
    title: data.articles[0].title,
    image: data.articles[0].urlToImage,
    description: data.articles[0].description,
    author: data.articles[0].author,
    link: data.articles[0].url,
    err: ""
    });


    Should be changed to something like the following.



    var articles = this.state.articles.slice();
    var newArticle = {
    title: data.articles[0].title,
    image: data.articles[0].urlToImage,
    description: data.articles[0].description,
    author: data.articles[0].author,
    link: data.articles[0].url,
    err: ""
    };
    articles.push(newArticle);

    this.setState(articles);


    Also note that setState is asynchronous. So sometimes, you should use the existing state to determine the new value of state. Refer setState documentation






    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53437343%2fsetstate-of-many-items-react%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      2 Answers
      2






      active

      oldest

      votes








      2 Answers
      2






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      So you want include all news items in state, then loop over them and create a News element for each of them. Something like this for the request:



      getNews = async e => {
      e.preventDefault();
      const country = e.target.elements.country.value;
      if (!country) {
      this.setState({
      articles: null,
      err: "Please enter valid country"
      });
      }
      let data;
      try {
      data = await fetch(this.buildURL(country)).then(res => res.json());
      } catch (error) {
      this.setState({
      articles: null,
      err: "Please enter valid country"
      });
      }
      if (data) {
      this.setState({
      articles: data.map(article => ({
      title: article.title,
      image: article.urlToImage,
      description: article.description,
      author: article.author,
      link: article.url
      }))
      });
      }
      };


      although I do not guarantee it is bug free!



      Then when you have all articles in state, you can loop over them:



      render() {
      return (
      <div>
      <Titles />
      <Form getNews={this.getNews} />

      {this.state.articles.map(article => (
      <News
      title={article.title}
      image={article.image}
      description={this.state.description}
      author={article.author}
      link={article.link}
      err={article.err}
      />
      ))}
      </div>
      );
      }


      or you can spread the props like this, if you know the object key names you stored in state match exactly those the News component expects:



        {this.state.articles.map(article => (
      <News {...article}/>
      ))}





      share|improve this answer


























        1














        So you want include all news items in state, then loop over them and create a News element for each of them. Something like this for the request:



        getNews = async e => {
        e.preventDefault();
        const country = e.target.elements.country.value;
        if (!country) {
        this.setState({
        articles: null,
        err: "Please enter valid country"
        });
        }
        let data;
        try {
        data = await fetch(this.buildURL(country)).then(res => res.json());
        } catch (error) {
        this.setState({
        articles: null,
        err: "Please enter valid country"
        });
        }
        if (data) {
        this.setState({
        articles: data.map(article => ({
        title: article.title,
        image: article.urlToImage,
        description: article.description,
        author: article.author,
        link: article.url
        }))
        });
        }
        };


        although I do not guarantee it is bug free!



        Then when you have all articles in state, you can loop over them:



        render() {
        return (
        <div>
        <Titles />
        <Form getNews={this.getNews} />

        {this.state.articles.map(article => (
        <News
        title={article.title}
        image={article.image}
        description={this.state.description}
        author={article.author}
        link={article.link}
        err={article.err}
        />
        ))}
        </div>
        );
        }


        or you can spread the props like this, if you know the object key names you stored in state match exactly those the News component expects:



          {this.state.articles.map(article => (
        <News {...article}/>
        ))}





        share|improve this answer
























          1












          1








          1






          So you want include all news items in state, then loop over them and create a News element for each of them. Something like this for the request:



          getNews = async e => {
          e.preventDefault();
          const country = e.target.elements.country.value;
          if (!country) {
          this.setState({
          articles: null,
          err: "Please enter valid country"
          });
          }
          let data;
          try {
          data = await fetch(this.buildURL(country)).then(res => res.json());
          } catch (error) {
          this.setState({
          articles: null,
          err: "Please enter valid country"
          });
          }
          if (data) {
          this.setState({
          articles: data.map(article => ({
          title: article.title,
          image: article.urlToImage,
          description: article.description,
          author: article.author,
          link: article.url
          }))
          });
          }
          };


          although I do not guarantee it is bug free!



          Then when you have all articles in state, you can loop over them:



          render() {
          return (
          <div>
          <Titles />
          <Form getNews={this.getNews} />

          {this.state.articles.map(article => (
          <News
          title={article.title}
          image={article.image}
          description={this.state.description}
          author={article.author}
          link={article.link}
          err={article.err}
          />
          ))}
          </div>
          );
          }


          or you can spread the props like this, if you know the object key names you stored in state match exactly those the News component expects:



            {this.state.articles.map(article => (
          <News {...article}/>
          ))}





          share|improve this answer












          So you want include all news items in state, then loop over them and create a News element for each of them. Something like this for the request:



          getNews = async e => {
          e.preventDefault();
          const country = e.target.elements.country.value;
          if (!country) {
          this.setState({
          articles: null,
          err: "Please enter valid country"
          });
          }
          let data;
          try {
          data = await fetch(this.buildURL(country)).then(res => res.json());
          } catch (error) {
          this.setState({
          articles: null,
          err: "Please enter valid country"
          });
          }
          if (data) {
          this.setState({
          articles: data.map(article => ({
          title: article.title,
          image: article.urlToImage,
          description: article.description,
          author: article.author,
          link: article.url
          }))
          });
          }
          };


          although I do not guarantee it is bug free!



          Then when you have all articles in state, you can loop over them:



          render() {
          return (
          <div>
          <Titles />
          <Form getNews={this.getNews} />

          {this.state.articles.map(article => (
          <News
          title={article.title}
          image={article.image}
          description={this.state.description}
          author={article.author}
          link={article.link}
          err={article.err}
          />
          ))}
          </div>
          );
          }


          or you can spread the props like this, if you know the object key names you stored in state match exactly those the News component expects:



            {this.state.articles.map(article => (
          <News {...article}/>
          ))}






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 22 at 21:31









          Cecil

          21125




          21125

























              0














              Your state should have an array instead of just provision for one object.



              this.setState({
              title: data.articles[0].title,
              image: data.articles[0].urlToImage,
              description: data.articles[0].description,
              author: data.articles[0].author,
              link: data.articles[0].url,
              err: ""
              });


              Should be changed to something like the following.



              var articles = this.state.articles.slice();
              var newArticle = {
              title: data.articles[0].title,
              image: data.articles[0].urlToImage,
              description: data.articles[0].description,
              author: data.articles[0].author,
              link: data.articles[0].url,
              err: ""
              };
              articles.push(newArticle);

              this.setState(articles);


              Also note that setState is asynchronous. So sometimes, you should use the existing state to determine the new value of state. Refer setState documentation






              share|improve this answer


























                0














                Your state should have an array instead of just provision for one object.



                this.setState({
                title: data.articles[0].title,
                image: data.articles[0].urlToImage,
                description: data.articles[0].description,
                author: data.articles[0].author,
                link: data.articles[0].url,
                err: ""
                });


                Should be changed to something like the following.



                var articles = this.state.articles.slice();
                var newArticle = {
                title: data.articles[0].title,
                image: data.articles[0].urlToImage,
                description: data.articles[0].description,
                author: data.articles[0].author,
                link: data.articles[0].url,
                err: ""
                };
                articles.push(newArticle);

                this.setState(articles);


                Also note that setState is asynchronous. So sometimes, you should use the existing state to determine the new value of state. Refer setState documentation






                share|improve this answer
























                  0












                  0








                  0






                  Your state should have an array instead of just provision for one object.



                  this.setState({
                  title: data.articles[0].title,
                  image: data.articles[0].urlToImage,
                  description: data.articles[0].description,
                  author: data.articles[0].author,
                  link: data.articles[0].url,
                  err: ""
                  });


                  Should be changed to something like the following.



                  var articles = this.state.articles.slice();
                  var newArticle = {
                  title: data.articles[0].title,
                  image: data.articles[0].urlToImage,
                  description: data.articles[0].description,
                  author: data.articles[0].author,
                  link: data.articles[0].url,
                  err: ""
                  };
                  articles.push(newArticle);

                  this.setState(articles);


                  Also note that setState is asynchronous. So sometimes, you should use the existing state to determine the new value of state. Refer setState documentation






                  share|improve this answer












                  Your state should have an array instead of just provision for one object.



                  this.setState({
                  title: data.articles[0].title,
                  image: data.articles[0].urlToImage,
                  description: data.articles[0].description,
                  author: data.articles[0].author,
                  link: data.articles[0].url,
                  err: ""
                  });


                  Should be changed to something like the following.



                  var articles = this.state.articles.slice();
                  var newArticle = {
                  title: data.articles[0].title,
                  image: data.articles[0].urlToImage,
                  description: data.articles[0].description,
                  author: data.articles[0].author,
                  link: data.articles[0].url,
                  err: ""
                  };
                  articles.push(newArticle);

                  this.setState(articles);


                  Also note that setState is asynchronous. So sometimes, you should use the existing state to determine the new value of state. Refer setState documentation







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 23 at 12:23









                  xadhix

                  14711




                  14711






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53437343%2fsetstate-of-many-items-react%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      What visual should I use to simply compare current year value vs last year in Power BI desktop

                      How to ignore python UserWarning in pytest?

                      Alexandru Averescu