Bind state to context value in React JS

45 Views Asked by At

I am very new to react. I have two components with two buttons and using context API to for global state. The values are updating in console log but not on the UI

Here is the code

App.jsx

import { useContext} from "react"
import Component1 from "./Component1"
import Component2 from "./Component2"
import { CounterContext } from "./CounterContext"
import CounterContextProvider from "./CounterContext"

function App() {
  const context = useContext(CounterContext)
  return <CounterContextProvider>
    <h1>Counter Value: {context.counterValue}</h1>
    <Component1/>
    <Component2/>
    </CounterContextProvider>
  }
  export default App

 Component1.jsx
  import { useContext } from "react"
  import { CounterContext } from "./CounterContext"
  export default function Component1() {
     const context = useContext(CounterContext);
     return <>
       <h1>Component 1</h1>
       <button onClick={context.handleIncrement}>Increment</button>
     </>
  }

Component2.jsx

import { useContext } from "react"
import { CounterContext } from "./CounterContext"
export default function Component2() {
   const context = useContext(CounterContext);
   return <>
    <h1>Component 2</h1>
    <button onClick={context.handleDecrement}>Decrement</button>
   </>
 }

import { createContext, useContext, useState } from "react";

export const CounterContext = createContext({
    counterValue: 10,
    handleIncrement: () => {},
    handleDecrement: () => {}
});

export default function CounterContextProvider({children}) {
   const context =useContext(CounterContext);
   const [counterState, setCounterState] = useState({counterValue: 10})
   
   function incrementValue() {
      console.log(counterState)
      let copiedObject = {...counterState}
      copiedObject.counterValue = copiedObject.counterValue + 1;
      setCounterState({...copiedObject})
   }

   function decrementValue() {
      let copiedObject = {...counterState}
      copiedObject.counterValue = copiedObject.counterValue - 1;
      setCounterState({...copiedObject})
   }

   let ctxValue = {
     counterValue: counterState.counterValue,
     handleIncrement: incrementValue,
     handleDecrement: decrementValue
   }

   return (
      <CounterContext.Provider value={ctxValue}>
          {children}
      </CounterContext.Provider>
   )
}

Here is the output image When I click on increment the value changes in logs but not updated in UI. Is there something I am doing wrong. I want to do this using context API only Output of project

0

There are 0 best solutions below