Home > Software design >  Simple counter isn't working with React context
Simple counter isn't working with React context

Time:11-15

I'm learning the React contexts and I tried to create a simple counter by using contexts to visualize the concept. Unfortunately, it doesn't work perfectly. The context works fine, but it doesn't work with simple arithmetic. What I mean by it's not working is that value doesn't show up after the incrementation.

I'm trying to reach the solution without using functional components.

The whole code is attached here and it's simple.

CounterContext.js

    import React, {Component, createContext} from "react"

export const CounterContext = createContext()

class CounterContextProvider extends Component {

    state = {
        ourNumber: 0
    }

    addOne = ()=> {
        console.log("addOne is reached")
        this.state.ourNumber = this.state.ourNumber   1
    }

    render() {
        return (
            <CounterContext.Provider value={{...this.state, addOne: this.addOne}}>
                {this.props.children}
            </CounterContext.Provider>
        )
    }
}

export default CounterContextProvider;

App.js

    import React, {Component} from 'react';
import CounterContextProvider from "./CounterContext";
import CounterPage from "./CounterPage";

class App extends Component {
    render() {
        return (
            <CounterContextProvider>
              <CounterPage/>
            </CounterContextProvider>
        );
    }
}

export default App;

CounterPage.js

    import React, {Component} from 'react';
import {CounterContext} from "./CounterContext";

class CounterPage extends Component {
    render() {
        return (
            <CounterContext.Consumer>
                {counterContext=>{
                    const {ourNumber, addOne} =counterContext

                    return(
                        <>
                            <h1> { ourNumber } </h1>
                            <p> { ourNumber } </p>
                            <button onClick={()=>{addOne()}}> 1</button>
                        </>
                    )
                }}
            </CounterContext.Consumer>
        );
    }
}

export default CounterPage;

CodePudding user response:

In order to change the state in class component you should use setState() like so:

addOne = () => {
    console.log("addOne is reached")
    this.setState({ourNumber: this.state.ourNumber   1})
}

https://reactjs.org/docs/react-component.html#setstate

  • Related