0

I am new to react. Could someone help me out on how an api call can be made repetitively every 15mins and the data be rendered onto the application? Please find the code below. I think using setInterval/setTimeout could be an option. But, which one is best and please help me out for my code below. Thanks in advance!

import React from 'react';
import axios from 'axios';

export default class UserList extends React.Component {
    state = {
        users: []
    };

    componentDidMount() {
        axios.get(`https://jsonplaceholder.typicode.com/users`)
            .then(res => {
                const users = res.data;
                this.setState({users});
            })
    }

    render() {
        return (
            <ul>
                {this.state.users.map(user => <li>{user.name}</li>)}
            </ul>
        )
    }
}
2
  • You can use any 1 of them and it should work but just curious, why you wanna make the request every 15 min(s). Is your requirement ask to show live data ? if yes then I guess you can go with setInterval or else simply introduce a refresh button and make the call when required. Commented May 8, 2020 at 12:16
  • Both works but since your are trying to run something at an interval, I would say go with setInterval. It's that it was meant for. Commented May 8, 2020 at 12:19

5 Answers 5

1

You can use any 1 of them and it should work but just curious, why you wanna make the request every 15 min(s). Is your requirement ask to show live data ? if yes then I guess you can go with setInterval as shown below or else simply introduce a refresh button and make the call when required

import React, { Component } from 'react';
import axios from 'axios';

const INTERVAL_DURATION = 15 * 1000 * 60;

export default class UserList extends Component {
  state = {
    users: [],
  };

  componentDidMount() {
    this._fetchUserInterval = setInterval(this._fetchUsers, INTERVAL_DURATION);
  }

  componentWillUmount() {
    clearInterval(this._fetchUserInterval);
  }

  _fetchUsers = () => {
    axios.get(`https://jsonplaceholder.typicode.com/users`).then(res => {
      this.setState({ users: res.data });
    });
  };

  render() {
    const { users } = this.state;

    return (
      <ul>
        {users.map((user, index) => (
          <li key={index}>{user.name}</li>
        ))}
      </ul>
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Try using setInterval() function -

componentDidMount() {
  setInterval(() => {
    axios.get(`https://jsonplaceholder.typicode.com/users`)
     .then(res => {
        const users = res.data;
        this.setState({users});
      });
  }, (15 * 1000 * 60));
}

Comments

1

Try this. Use setInterval and store the intervalId so you can clean up when the component unmounts.

import React from 'react';
import axios from 'axios';

export default class UserList extends React.Component {
    state = {
        users: [],
    };

    componentDidMount() {
        // Keep the interval id
        this.intervalId = setInterval(this.getData, 900000);
    }

    componentWillUnmount() {
        // use intervalId to clear the interval onUnmount
        clearInterval(this.intervalId);
    }

    getData() {
        axios.get(`https://jsonplaceholder.typicode.com/users`)
            .then(res => {
                const users = res.data;
                this.setState({ users });
            })
            .catch(error => console.log(error))
    }

    render() {
        return (
            <ul>
                {this.state.users.map(user => <li>{user.name}</li>)}
            </ul>
        )
    }
}

Comments

1

setTimeout() triggers only once, while for repetitive task setInterval() is the option.

You can go this way

componentDidMount() {
  setInterval(() => {
    axios.get(`https://jsonplaceholder.typicode.com/users.then(res => {
        const users = res.data;
        this.setState({users});
      });
  }, (15 * 1000 * 60));
}

Also, as it is a class component you will have to clear all subscriptions in componentWillUnmount() or getDerivedStateFromProps().

Extra note: Always use keys while iterating in JSX.

render() {
        return (
            <ul>
                {this.state.users.map((user, index) 
                    => <li key={index}>{user.name}</li>)}
            </ul>
        )
    }

Comments

0

Both should work but using setInterval will be an easier option.

Comments

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.