Here is a CodeSandbox that has the example code below, and the linter highlights some of the issues: https://codesandbox.io/s/react-repl-bw2h1
Below is a basic example of what I'm trying to do. In a container component, I have a context AppContext
that is providing state to child components, <ChildConsumer />
and <ChildDispatcher />
.
The <ChildConsumer />
component is receiving this state using useContext
, and this seems to be working as expected.
Inside <ChildDispatcher />
, I'm trying to dispatch an action when a button is clicked. To do this, I've created a reducer reducer
that handles an action. I've also set up useReducer here that takes in reducer
and the initial store
state.
When I click the button, nothing happens. What I'm expecting to happen is that the dispatch
receives both the state
pulled off of useReducer
as well as an action
object, and passes these to the reducer. The reducer should see that the action of type BUTTON_CLICKED
was received, and should return a new state containing the old state as well as an additional 'goodbye'
item. Then, the child component <ChildConsumer />
should rerender with this new state.
import React, { createContext, useContext, useReducer } from "react";
import ReactDOM from "react-dom";
const store = [""];
const AppContext = createContext(store);
const ChildDispatcher = () => {
const reducer = (state, action) => {
switch (action.type) {
case "BUTTON_CLICKED":
return [...state, "goodbye"];
default:
return state;
}
};
const [state, dispatch] = useReducer(reducer, store);
const handleClick = () =>
dispatch(state, {
type: "BUTTON_CLICKED"
});
return <button onClick={handleClick}>press me</button>;
};
const ChildConsumer = () => {
const [consumer] = useContext(AppContext);
return <div>{consumer}</div>;
};
const App = () => {
return (
<div>
<h1>Using Context and useReducer</h1>
<AppContext.Provider value={["hello"]}>
<ChildConsumer />
<ChildDispatcher />
</AppContext.Provider>
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
I have made a small amendment in you code.
you have to pass the dispatch like below. Dispatch expects an argument of type object.
const handleClick = () => dispatch({ type: "BUTTON_CLICKED" });
And then this state could be accessed like this.
const ChildDispatcher = () => {
const reducer = (state, action) => {
switch (action.type) {
case "BUTTON_CLICKED":
//action.state // like this
return [...state, "goodbye"];
default:
return state;
}
};
const [state, dispatch] = useReducer(reducer, store);
const handleClick = () =>
dispatch(state, {
type: "BUTTON_CLICKED"
});
return <button onClick={handleClick}>press me</button>;
};
By default react will pass the state to the dispatcher. but if you want to pass some data the you can add it in the object and pass that object to dispatch.
const handleClick = () => dispatch({ type: "BUTTON_CLICKED", state: state });
CodeSandBox: