Is there a way i can get access of a component's state to another component through useReducer and Context API?

50 Views Asked by At

I found this code in a youtube video in which a counter in App.js is global and is being controlled by button in the app component as well as by buttons in other components by passing a function on click event of button that dispatches an action

//code for Child component

import { CountContext } from "../App";

function ComponentA() {
    const countContext = useContext(CountContext);

    // const display = () => {
    //  // countContext.countState();
    //  console.log("comp a", countContext.countSState("increment"));
    // };
    return (
        <div>
            Component A {countContext.countState}
            <button onClick={() => countContext.countDispatch("increment")}>
                Increment
            </button>
            <button onClick={() => countContext.countDispatch("decrement")}>
                Decrement
            </button>
            <button onClick={() => countContext.countDispatch("reset")}>Reset</button>
      
            <button onClick={display}>Acessing the app state</button> 
        </div>
    );
}

//code for App.js

export const CountContext = React.createContext();

function App() {
    const [count, dispatch] = useReducer(reducer, initialState);

    const incFunc = () => {
        dispatch("increment");
        console.log("dispatch", count);
        console.log("dispatched", dispatch);
    };

    return (
        <CountContext.Provider value={{ countState: count, countDispatch: dispatch }}>
            <div className="App">
                <CounterOne />
                <CounterTwo />
                <CounterThree />
                {count}
                <button onClick={incFunc}>Inc</button>
                <ComponentA />
                <ComponentB />
                <ComponentC />
                <DataFetchingOne />
                <DataFetchingTwo />
            </div>
        </CountContext.Provider>
    );
}

The commented display function in child component is my editing in the code for accessing the initial state and i'm trying to call this in the very last button named Accessing the app state but nothing gets printed on the console when i click this button. I want to access the value of count that is being updated in inFunc of App Component in the child component. I've no clue how to do this.

1

There are 1 best solutions below

0
On BEST ANSWER
console.log("comp a", countContext.countState);

countState is not a function. Also, you have a typo in console log statement.

Working example: https://codesandbox.io/s/peaceful-violet-01e3x

I will delete this example after 24 hours.