Home > Software engineering >  Update Component on State Change - REACT
Update Component on State Change - REACT

Time:10-12

I am just starting out with React and have already found myself in a loop. I am building an app that fetches data from a Flask API. Got everything set up so far, but I don't want to display all data on the first page. Rather, I want to split the data from the API and display it 10 at a time.

My problem is that I manage to split the data, but the DOM won't update on state change. Here is my code so far:

import React from 'react';
import Navbar from './Components/Navbar';
import Home from './Components/Home';
import {BrowserRouter as Router, Route, useHistory} from 'react-router-dom'
import Button from '@restart/ui/esm/Button';

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
        number: 10
    }
  }
 
  updateContent = (prevState) => {
      this.setState({number: this.state.number   10});
  }
 
  render() {
    return (
      <Router>
        <Navbar />
        <Home perPage={this.state.number} />
            <div class="text-center mt-3 mb-3">
              {this.state.number}
              <Button className='btn btn-primary' onClick={this.updateContent}>Mai multe intrebari</Button>
            </div>
      </Router>
    );
  }
}

export default App;

Even though number is update and I can display the updated {this.state.number} in DOM (in same div as Button), changing it does not update my Home component:

    <Home perPage={this.state.number} />

where perPage is a prop that I use to fetch data from my API:

useEffect(() => {
    fetch("my_flask_api/v1/?id="   props.perPage)
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
        },

PS: It works if I manually change number's value and it updates the DOM correctly, but it won't do it on setState().

Any ideas are welcome. Thanks in advance!

CodePudding user response:

There are two things that you need to take care of:

  1. this.setState(prevState => ({number: prevState.number 10}));
  2. your useEffect should have props.perPage as dependancy in the array so it gets the most recently updated value useEffect(() => {...} , [props.perPage])
  • Related