Mick D
Mick D

Reputation: 172

Right way to update data in ReactJS

what is the right way in ReactJS to update and display the correct value.

Example: I show data on the screen from a database. When I change the values in the database I want to see the new values directly on the screen.

I have two files:

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

    this.state = {
        containers: []
    };
}

componentDidMount() {
    var self = this;

    axios.get('http://reactlaravel.dev/container/count').then(function (response) {
        self.setState({
            containers: response.data
        });
    })
}

render() {
    const containers = this.state.containers.map( (container, i) => <StockCount key={i} {...container} /> );

    return (
        <div>
            {containers}
        </div>
    )
}

const Container = ({ name, total, current }) => (
<div>
    <span>{name}</span>
    <span>{total}</span>
    <span>{current}</span>
</div>
);

ReactDOM.render(
    <Parent />,
    document.getElementById('app')
);

And the second file:

export class StockCount extends React.Component {
    render() {
        const currentBar = this.props.current;
        const totalBar = this.props.total;
        const progressBar = currentBar / totalBar * 100;

        return (
            <div className="container">
                <h1>{this.props.current} - {this.props.total} -  {this.props.name}</h1>

            <div className="progress">
                <div className={progressBarType} role="progressbar" aria-valuenow={progressBar} aria-valuemin="0" aria-valuemax="100" style={style}>
                    <span className="sr-only">{progressBar}% Complete (success)</span>
                </div>
            </div>
        </div>
    );
}

Upvotes: 1

Views: 15884

Answers (2)

Vlad
Vlad

Reputation: 479

You have to implement server push (will require server changes) in order to notify client app about database changes. Here is easiest way to go without server modifications short pulling:

componentDidMount() {
  this.lookupInterval = setInterval(() => {
     axios
        .get('http://reactlaravel.dev/container/count')
        .then(function(response) {
        this.setState({
            containers: response.data,
        })
        })
  }, 500)
}
componentWillUnMount() {
    clearInterval(this.lookupInterval)
}

Upvotes: 1

Maja Okholm
Maja Okholm

Reputation: 3337

Use a life cycle method for updating? like componentWillReceiveProps() https://reactjs.org/docs/react-component.html

Upvotes: 0

Related Questions