0

stackoverflow, I'm really new to React, can you show me please, what I'm doing wrong, thank you!

This code is really simple, so I included all

class Buttons extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            totalPages: 0,
            currentPage: 1
        }
    }

    loadPage = (value) => {
        let page = this.state.currentPage
        
       
        if (this.props.value === "Previous Page"){
            this.setState(state => ({
                currentPage: page - 1
            }));
            page = this.state.currentPage
            console.log(`Changing to -1, state.currentPage: ${this.state.currentPage}, page ${page}`)
        }
        if (this.props.value === "Next Page"){
            this.setState(state => ({
                currentPage: page + 1
            }));
            page = this.state.currentPage
            console.log(`Changing to +1, state.currentPage: ${this.state.currentPage}, page ${page}`)
        }

            
        
    }
class Menu extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            page: 0,
            totalPages: 0
        }
    }

    render() {
        return (
            <div>
                <nav aria-label="Page navigation example">
                    <ul className="pagination">
                    <Buttons value = "Next Page"/>
                    <Buttons value = "Previous Page"/>
                    </ul>
                </nav> 
            </div>
        );
    }

This is a result, which I got from the Chrome console. enter image description here

It looks like, React not changing the state, but making a new instance of the object, but I have no idea how to fix that.

Ledary
  • 21
  • 4
  • 1
    `this.setState` sets the value in state async, the new value is not guaranteed to be present in the state until the next render. – Jacob Smit Feb 22 '21 at 20:18
  • 1
    The biggest issue is that `setState` is async, so immediately logging the state is pointless. Second is that you're using the right *form* of `setState` when it relies on the previous state, but promptly ignoring the current state and using whatever is in `page` instead. – Dave Newton Feb 22 '21 at 20:19

0 Answers0