Getting undefined when trying to fetch data from an api - React












0















So im trying to set a variable with the data im getting from the API.



when im console logging it into my browser everything works fine but when im trying to set my variable on React the variable ending up undifeind.
can someone tell me what am i missing here?



this is my code :



import React from 'react'

let news
function getNews () {
fetch(
'https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9'
)
.then(res => res.json())
.then(data => {
news = data
return news
})
}

getNews()
class NewsApi extends React.Component {
render () {
return <div />
}
}

export default NewsApi









share|improve this question

























  • Check my answer, mark accepted if it works for you.

    – Tarreq
    Jan 1 at 20:39
















0















So im trying to set a variable with the data im getting from the API.



when im console logging it into my browser everything works fine but when im trying to set my variable on React the variable ending up undifeind.
can someone tell me what am i missing here?



this is my code :



import React from 'react'

let news
function getNews () {
fetch(
'https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9'
)
.then(res => res.json())
.then(data => {
news = data
return news
})
}

getNews()
class NewsApi extends React.Component {
render () {
return <div />
}
}

export default NewsApi









share|improve this question

























  • Check my answer, mark accepted if it works for you.

    – Tarreq
    Jan 1 at 20:39














0












0








0








So im trying to set a variable with the data im getting from the API.



when im console logging it into my browser everything works fine but when im trying to set my variable on React the variable ending up undifeind.
can someone tell me what am i missing here?



this is my code :



import React from 'react'

let news
function getNews () {
fetch(
'https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9'
)
.then(res => res.json())
.then(data => {
news = data
return news
})
}

getNews()
class NewsApi extends React.Component {
render () {
return <div />
}
}

export default NewsApi









share|improve this question
















So im trying to set a variable with the data im getting from the API.



when im console logging it into my browser everything works fine but when im trying to set my variable on React the variable ending up undifeind.
can someone tell me what am i missing here?



this is my code :



import React from 'react'

let news
function getNews () {
fetch(
'https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9'
)
.then(res => res.json())
.then(data => {
news = data
return news
})
}

getNews()
class NewsApi extends React.Component {
render () {
return <div />
}
}

export default NewsApi






reactjs






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 2 at 5:50









Naor Tedgi

1,1651921




1,1651921










asked Jan 1 at 19:41









ShibexShibex

216




216













  • Check my answer, mark accepted if it works for you.

    – Tarreq
    Jan 1 at 20:39



















  • Check my answer, mark accepted if it works for you.

    – Tarreq
    Jan 1 at 20:39

















Check my answer, mark accepted if it works for you.

– Tarreq
Jan 1 at 20:39





Check my answer, mark accepted if it works for you.

– Tarreq
Jan 1 at 20:39












3 Answers
3






active

oldest

votes


















1














Your getNews function is async. You should use state to save your data. So, as soon as the data fetched, you can use the data in your component.



import React from 'react';

class NewsApi extends React.Component {
constructor(props) {
super(props);
this.state = {
news:
};
this.getNews = this.getNews.bind(this);
}

componentDidMount() {
this.getNews()
}

getNews() {
fetch('https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9')
.then(res => res.json())
.then((data) => {
this.setState({news:data.articles});
});
}

render() {
console.log(this.state.news)
return (
<div></div>
);
}
}

export default NewsApi;





share|improve this answer
























  • Thanks your replay. Didn’t check if it works yet. But i am just wondering. Is there any way with react around the state solution ? I mean, i cannot use global variables in this case?

    – Shibex
    Jan 1 at 20:59











  • If you need to use the data in your component, you should use state. Because fetch is async and we never know when the data is fetched. Another way is to use callback func or observer for the value. I think the most painless way in react, using states or global states(redux or flux)

    – sdkcy
    Jan 1 at 21:12



















0














try this : It outputs what you want.
** Notes:
Fetch is Async functions, means, it has to be called inside (for example) life cycle method like componentDidMount.



import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component {
constructor(props) {
super(props);

this.state = {
news:
};
}

componentDidMount() {
fetch(
"https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
)
.then(response => response.json())
.then(data => this.setState({ news: data.articles }));
}

render() {
console.log(this.state.news);
return <div />;
}
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);


Here is a live example (You can see console output also)



Edit 487m15996x






share|improve this answer































    0














    Please look at the snippet below for an example implementation.



    Some key points:




    • Try to do your data fetching in componentDidMount()

    • Use state and this.setState()

      This will cause an automatic rerender after the data is fetched.

      Handy for working with asynchronous function calls: these tools make it easy to use data in components without knowing when it will become available and help eliminate the undefined issue you were having.





    class NewsApi extends React.Component {
    state = {
    articles:
    };

    componentDidMount() {
    fetch(
    "https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
    )
    .then(res => res.json())
    .then(data => data.articles)
    .then(articles => {
    this.setState({ articles });
    });
    }

    render() {
    return (
    <div>
    <h1>Articles</h1>
    <ArticleList articles={this.state.articles} />
    </div>
    );
    }
    }

    const ArticleList = props => (
    <div>
    <ol>
    {props.articles.map((article, index) => (
    <div key={index}>
    <li>{article.title}</li>
    <br />
    </div>
    ))}
    </ol>
    </div>
    );

    function App() {
    const appStyle = {
    fontFamily: "sans-serif",
    textAlign: "center"
    };

    return (
    <div className="App" style={appStyle}>
    <NewsApi />
    </div>
    );
    }

    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
    <div id="root"></div>








    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%2f53998407%2fgetting-undefined-when-trying-to-fetch-data-from-an-api-react%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      Your getNews function is async. You should use state to save your data. So, as soon as the data fetched, you can use the data in your component.



      import React from 'react';

      class NewsApi extends React.Component {
      constructor(props) {
      super(props);
      this.state = {
      news:
      };
      this.getNews = this.getNews.bind(this);
      }

      componentDidMount() {
      this.getNews()
      }

      getNews() {
      fetch('https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9')
      .then(res => res.json())
      .then((data) => {
      this.setState({news:data.articles});
      });
      }

      render() {
      console.log(this.state.news)
      return (
      <div></div>
      );
      }
      }

      export default NewsApi;





      share|improve this answer
























      • Thanks your replay. Didn’t check if it works yet. But i am just wondering. Is there any way with react around the state solution ? I mean, i cannot use global variables in this case?

        – Shibex
        Jan 1 at 20:59











      • If you need to use the data in your component, you should use state. Because fetch is async and we never know when the data is fetched. Another way is to use callback func or observer for the value. I think the most painless way in react, using states or global states(redux or flux)

        – sdkcy
        Jan 1 at 21:12
















      1














      Your getNews function is async. You should use state to save your data. So, as soon as the data fetched, you can use the data in your component.



      import React from 'react';

      class NewsApi extends React.Component {
      constructor(props) {
      super(props);
      this.state = {
      news:
      };
      this.getNews = this.getNews.bind(this);
      }

      componentDidMount() {
      this.getNews()
      }

      getNews() {
      fetch('https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9')
      .then(res => res.json())
      .then((data) => {
      this.setState({news:data.articles});
      });
      }

      render() {
      console.log(this.state.news)
      return (
      <div></div>
      );
      }
      }

      export default NewsApi;





      share|improve this answer
























      • Thanks your replay. Didn’t check if it works yet. But i am just wondering. Is there any way with react around the state solution ? I mean, i cannot use global variables in this case?

        – Shibex
        Jan 1 at 20:59











      • If you need to use the data in your component, you should use state. Because fetch is async and we never know when the data is fetched. Another way is to use callback func or observer for the value. I think the most painless way in react, using states or global states(redux or flux)

        – sdkcy
        Jan 1 at 21:12














      1












      1








      1







      Your getNews function is async. You should use state to save your data. So, as soon as the data fetched, you can use the data in your component.



      import React from 'react';

      class NewsApi extends React.Component {
      constructor(props) {
      super(props);
      this.state = {
      news:
      };
      this.getNews = this.getNews.bind(this);
      }

      componentDidMount() {
      this.getNews()
      }

      getNews() {
      fetch('https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9')
      .then(res => res.json())
      .then((data) => {
      this.setState({news:data.articles});
      });
      }

      render() {
      console.log(this.state.news)
      return (
      <div></div>
      );
      }
      }

      export default NewsApi;





      share|improve this answer













      Your getNews function is async. You should use state to save your data. So, as soon as the data fetched, you can use the data in your component.



      import React from 'react';

      class NewsApi extends React.Component {
      constructor(props) {
      super(props);
      this.state = {
      news:
      };
      this.getNews = this.getNews.bind(this);
      }

      componentDidMount() {
      this.getNews()
      }

      getNews() {
      fetch('https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9')
      .then(res => res.json())
      .then((data) => {
      this.setState({news:data.articles});
      });
      }

      render() {
      console.log(this.state.news)
      return (
      <div></div>
      );
      }
      }

      export default NewsApi;






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Jan 1 at 20:20









      sdkcysdkcy

      86139




      86139













      • Thanks your replay. Didn’t check if it works yet. But i am just wondering. Is there any way with react around the state solution ? I mean, i cannot use global variables in this case?

        – Shibex
        Jan 1 at 20:59











      • If you need to use the data in your component, you should use state. Because fetch is async and we never know when the data is fetched. Another way is to use callback func or observer for the value. I think the most painless way in react, using states or global states(redux or flux)

        – sdkcy
        Jan 1 at 21:12



















      • Thanks your replay. Didn’t check if it works yet. But i am just wondering. Is there any way with react around the state solution ? I mean, i cannot use global variables in this case?

        – Shibex
        Jan 1 at 20:59











      • If you need to use the data in your component, you should use state. Because fetch is async and we never know when the data is fetched. Another way is to use callback func or observer for the value. I think the most painless way in react, using states or global states(redux or flux)

        – sdkcy
        Jan 1 at 21:12

















      Thanks your replay. Didn’t check if it works yet. But i am just wondering. Is there any way with react around the state solution ? I mean, i cannot use global variables in this case?

      – Shibex
      Jan 1 at 20:59





      Thanks your replay. Didn’t check if it works yet. But i am just wondering. Is there any way with react around the state solution ? I mean, i cannot use global variables in this case?

      – Shibex
      Jan 1 at 20:59













      If you need to use the data in your component, you should use state. Because fetch is async and we never know when the data is fetched. Another way is to use callback func or observer for the value. I think the most painless way in react, using states or global states(redux or flux)

      – sdkcy
      Jan 1 at 21:12





      If you need to use the data in your component, you should use state. Because fetch is async and we never know when the data is fetched. Another way is to use callback func or observer for the value. I think the most painless way in react, using states or global states(redux or flux)

      – sdkcy
      Jan 1 at 21:12













      0














      try this : It outputs what you want.
      ** Notes:
      Fetch is Async functions, means, it has to be called inside (for example) life cycle method like componentDidMount.



      import React from "react";
      import ReactDOM from "react-dom";

      import "./styles.css";

      class App extends React.Component {
      constructor(props) {
      super(props);

      this.state = {
      news:
      };
      }

      componentDidMount() {
      fetch(
      "https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
      )
      .then(response => response.json())
      .then(data => this.setState({ news: data.articles }));
      }

      render() {
      console.log(this.state.news);
      return <div />;
      }
      }

      const rootElement = document.getElementById("root");
      ReactDOM.render(<App />, rootElement);


      Here is a live example (You can see console output also)



      Edit 487m15996x






      share|improve this answer




























        0














        try this : It outputs what you want.
        ** Notes:
        Fetch is Async functions, means, it has to be called inside (for example) life cycle method like componentDidMount.



        import React from "react";
        import ReactDOM from "react-dom";

        import "./styles.css";

        class App extends React.Component {
        constructor(props) {
        super(props);

        this.state = {
        news:
        };
        }

        componentDidMount() {
        fetch(
        "https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
        )
        .then(response => response.json())
        .then(data => this.setState({ news: data.articles }));
        }

        render() {
        console.log(this.state.news);
        return <div />;
        }
        }

        const rootElement = document.getElementById("root");
        ReactDOM.render(<App />, rootElement);


        Here is a live example (You can see console output also)



        Edit 487m15996x






        share|improve this answer


























          0












          0








          0







          try this : It outputs what you want.
          ** Notes:
          Fetch is Async functions, means, it has to be called inside (for example) life cycle method like componentDidMount.



          import React from "react";
          import ReactDOM from "react-dom";

          import "./styles.css";

          class App extends React.Component {
          constructor(props) {
          super(props);

          this.state = {
          news:
          };
          }

          componentDidMount() {
          fetch(
          "https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
          )
          .then(response => response.json())
          .then(data => this.setState({ news: data.articles }));
          }

          render() {
          console.log(this.state.news);
          return <div />;
          }
          }

          const rootElement = document.getElementById("root");
          ReactDOM.render(<App />, rootElement);


          Here is a live example (You can see console output also)



          Edit 487m15996x






          share|improve this answer













          try this : It outputs what you want.
          ** Notes:
          Fetch is Async functions, means, it has to be called inside (for example) life cycle method like componentDidMount.



          import React from "react";
          import ReactDOM from "react-dom";

          import "./styles.css";

          class App extends React.Component {
          constructor(props) {
          super(props);

          this.state = {
          news:
          };
          }

          componentDidMount() {
          fetch(
          "https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
          )
          .then(response => response.json())
          .then(data => this.setState({ news: data.articles }));
          }

          render() {
          console.log(this.state.news);
          return <div />;
          }
          }

          const rootElement = document.getElementById("root");
          ReactDOM.render(<App />, rootElement);


          Here is a live example (You can see console output also)



          Edit 487m15996x







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Jan 1 at 20:38









          TarreqTarreq

          578212




          578212























              0














              Please look at the snippet below for an example implementation.



              Some key points:




              • Try to do your data fetching in componentDidMount()

              • Use state and this.setState()

                This will cause an automatic rerender after the data is fetched.

                Handy for working with asynchronous function calls: these tools make it easy to use data in components without knowing when it will become available and help eliminate the undefined issue you were having.





              class NewsApi extends React.Component {
              state = {
              articles:
              };

              componentDidMount() {
              fetch(
              "https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
              )
              .then(res => res.json())
              .then(data => data.articles)
              .then(articles => {
              this.setState({ articles });
              });
              }

              render() {
              return (
              <div>
              <h1>Articles</h1>
              <ArticleList articles={this.state.articles} />
              </div>
              );
              }
              }

              const ArticleList = props => (
              <div>
              <ol>
              {props.articles.map((article, index) => (
              <div key={index}>
              <li>{article.title}</li>
              <br />
              </div>
              ))}
              </ol>
              </div>
              );

              function App() {
              const appStyle = {
              fontFamily: "sans-serif",
              textAlign: "center"
              };

              return (
              <div className="App" style={appStyle}>
              <NewsApi />
              </div>
              );
              }

              const rootElement = document.getElementById("root");
              ReactDOM.render(<App />, rootElement);

              <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
              <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
              <div id="root"></div>








              share|improve this answer






























                0














                Please look at the snippet below for an example implementation.



                Some key points:




                • Try to do your data fetching in componentDidMount()

                • Use state and this.setState()

                  This will cause an automatic rerender after the data is fetched.

                  Handy for working with asynchronous function calls: these tools make it easy to use data in components without knowing when it will become available and help eliminate the undefined issue you were having.





                class NewsApi extends React.Component {
                state = {
                articles:
                };

                componentDidMount() {
                fetch(
                "https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
                )
                .then(res => res.json())
                .then(data => data.articles)
                .then(articles => {
                this.setState({ articles });
                });
                }

                render() {
                return (
                <div>
                <h1>Articles</h1>
                <ArticleList articles={this.state.articles} />
                </div>
                );
                }
                }

                const ArticleList = props => (
                <div>
                <ol>
                {props.articles.map((article, index) => (
                <div key={index}>
                <li>{article.title}</li>
                <br />
                </div>
                ))}
                </ol>
                </div>
                );

                function App() {
                const appStyle = {
                fontFamily: "sans-serif",
                textAlign: "center"
                };

                return (
                <div className="App" style={appStyle}>
                <NewsApi />
                </div>
                );
                }

                const rootElement = document.getElementById("root");
                ReactDOM.render(<App />, rootElement);

                <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
                <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
                <div id="root"></div>








                share|improve this answer




























                  0












                  0








                  0







                  Please look at the snippet below for an example implementation.



                  Some key points:




                  • Try to do your data fetching in componentDidMount()

                  • Use state and this.setState()

                    This will cause an automatic rerender after the data is fetched.

                    Handy for working with asynchronous function calls: these tools make it easy to use data in components without knowing when it will become available and help eliminate the undefined issue you were having.





                  class NewsApi extends React.Component {
                  state = {
                  articles:
                  };

                  componentDidMount() {
                  fetch(
                  "https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
                  )
                  .then(res => res.json())
                  .then(data => data.articles)
                  .then(articles => {
                  this.setState({ articles });
                  });
                  }

                  render() {
                  return (
                  <div>
                  <h1>Articles</h1>
                  <ArticleList articles={this.state.articles} />
                  </div>
                  );
                  }
                  }

                  const ArticleList = props => (
                  <div>
                  <ol>
                  {props.articles.map((article, index) => (
                  <div key={index}>
                  <li>{article.title}</li>
                  <br />
                  </div>
                  ))}
                  </ol>
                  </div>
                  );

                  function App() {
                  const appStyle = {
                  fontFamily: "sans-serif",
                  textAlign: "center"
                  };

                  return (
                  <div className="App" style={appStyle}>
                  <NewsApi />
                  </div>
                  );
                  }

                  const rootElement = document.getElementById("root");
                  ReactDOM.render(<App />, rootElement);

                  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
                  <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
                  <div id="root"></div>








                  share|improve this answer















                  Please look at the snippet below for an example implementation.



                  Some key points:




                  • Try to do your data fetching in componentDidMount()

                  • Use state and this.setState()

                    This will cause an automatic rerender after the data is fetched.

                    Handy for working with asynchronous function calls: these tools make it easy to use data in components without knowing when it will become available and help eliminate the undefined issue you were having.





                  class NewsApi extends React.Component {
                  state = {
                  articles:
                  };

                  componentDidMount() {
                  fetch(
                  "https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
                  )
                  .then(res => res.json())
                  .then(data => data.articles)
                  .then(articles => {
                  this.setState({ articles });
                  });
                  }

                  render() {
                  return (
                  <div>
                  <h1>Articles</h1>
                  <ArticleList articles={this.state.articles} />
                  </div>
                  );
                  }
                  }

                  const ArticleList = props => (
                  <div>
                  <ol>
                  {props.articles.map((article, index) => (
                  <div key={index}>
                  <li>{article.title}</li>
                  <br />
                  </div>
                  ))}
                  </ol>
                  </div>
                  );

                  function App() {
                  const appStyle = {
                  fontFamily: "sans-serif",
                  textAlign: "center"
                  };

                  return (
                  <div className="App" style={appStyle}>
                  <NewsApi />
                  </div>
                  );
                  }

                  const rootElement = document.getElementById("root");
                  ReactDOM.render(<App />, rootElement);

                  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
                  <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
                  <div id="root"></div>








                  class NewsApi extends React.Component {
                  state = {
                  articles:
                  };

                  componentDidMount() {
                  fetch(
                  "https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
                  )
                  .then(res => res.json())
                  .then(data => data.articles)
                  .then(articles => {
                  this.setState({ articles });
                  });
                  }

                  render() {
                  return (
                  <div>
                  <h1>Articles</h1>
                  <ArticleList articles={this.state.articles} />
                  </div>
                  );
                  }
                  }

                  const ArticleList = props => (
                  <div>
                  <ol>
                  {props.articles.map((article, index) => (
                  <div key={index}>
                  <li>{article.title}</li>
                  <br />
                  </div>
                  ))}
                  </ol>
                  </div>
                  );

                  function App() {
                  const appStyle = {
                  fontFamily: "sans-serif",
                  textAlign: "center"
                  };

                  return (
                  <div className="App" style={appStyle}>
                  <NewsApi />
                  </div>
                  );
                  }

                  const rootElement = document.getElementById("root");
                  ReactDOM.render(<App />, rootElement);

                  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
                  <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
                  <div id="root"></div>





                  class NewsApi extends React.Component {
                  state = {
                  articles:
                  };

                  componentDidMount() {
                  fetch(
                  "https://newsapi.org/v2/top-headlines?country=us&apiKey=6f9cf5e6b9684bd3a6a8117e35feb1c9"
                  )
                  .then(res => res.json())
                  .then(data => data.articles)
                  .then(articles => {
                  this.setState({ articles });
                  });
                  }

                  render() {
                  return (
                  <div>
                  <h1>Articles</h1>
                  <ArticleList articles={this.state.articles} />
                  </div>
                  );
                  }
                  }

                  const ArticleList = props => (
                  <div>
                  <ol>
                  {props.articles.map((article, index) => (
                  <div key={index}>
                  <li>{article.title}</li>
                  <br />
                  </div>
                  ))}
                  </ol>
                  </div>
                  );

                  function App() {
                  const appStyle = {
                  fontFamily: "sans-serif",
                  textAlign: "center"
                  };

                  return (
                  <div className="App" style={appStyle}>
                  <NewsApi />
                  </div>
                  );
                  }

                  const rootElement = document.getElementById("root");
                  ReactDOM.render(<App />, rootElement);

                  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.1/umd/react.production.min.js"></script>
                  <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.1/umd/react-dom.production.min.js"></script>
                  <div id="root"></div>






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jan 1 at 21:20

























                  answered Jan 1 at 20:58









                  Laurens DeprostLaurens Deprost

                  968114




                  968114






























                      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.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53998407%2fgetting-undefined-when-trying-to-fetch-data-from-an-api-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

                      MongoDB - Not Authorized To Execute Command

                      How to fix TextFormField cause rebuild widget in Flutter

                      in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith