Advertisement
Guest User

Untitled

a guest
Jul 16th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  1. /* Most web developers, at some point, need to call an API endpoint to retrieve data. If you're working with React,
  2. it's important to know where to perform this action. The best practice with React is to place API calls or any calls
  3. to your server in the lifecycle method componentDidMount(). This method is called after a component is mounted to the DOM.
  4. Any calls to setState() here will trigger a re-rendering of your component. When you call an API in this method, and set your
  5. state with the data that the API returns, it will automatically trigger an update once you receive the data.
  6.  
  7. There is a mock API call in componentDidMount(). It sets state after 2.5 seconds to simulate calling a server to retrieve data.
  8. This example requests the current total active users for a site. In the render method, render the value of activeUsers in the h1.
  9. Watch what happens in the preview, and feel free to change the timeout to see the different effects.
  10.  
  11. */
  12.  
  13. class MyComponent extends React.Component {
  14. constructor(props) {
  15. super(props);
  16. this.state = {
  17. activeUsers: null
  18. };
  19. }
  20. componentDidMount() {
  21. setTimeout( () => {
  22. this.setState({
  23. activeUsers: 1273
  24. });
  25. }, 2500);
  26. }
  27. render() {
  28. return (
  29. <div>
  30. <h1>Active Users: { this.state.activeUsers/* change code here */ }</h1>
  31. </div>
  32. );
  33. }
  34. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement