I am having trouble getting reducer to work with React context. In buttonbar.js
, there are two buttons that are supposed to update the state. The state will be updated by filtering the data in the current. The buttons are being clicked and I don't get any errors, but it's also not doing anything. I think the issue is with the reducer.
context.js
import React, { useState, useEffect } from "react";
import * as moment from "moment";
import axios from "axios";
export const Context = React.createContext();
const url = "https://projects.fivethirtyeight.com/polls/polls.json";
export const filterReducer = (state, action) => {
switch (action.type) {
case "SHOW_ALL":
return state.polls;
case "SHOW_APPROVAL":
return state.polls.filter(e => e.type === "trump-approval");
default:
return state.polls;
}
};
export function Provider({ children }) {
let intialState = {
polls: [],
dispatch: action => this.setState(state => filterReducer(state, action))
};
const [state, setState, dispatch] = useState(intialState);
useEffect(() => {
var dateRange = moment()
.subtract(7, "days")
.calendar();
axios
.get(url)
.then(res => {
setState({
polls: res.data
.filter(e => Date.parse(e.endDate) >= Date.parse(dateRange))
.reverse()
});
}, [])
.catch(error => console.log(error));
}, []);
return (
<Context.Provider value={[state, setState, dispatch]}>
{children}
</Context.Provider>
);
}
// export const Consumer = Context.Consumer;
buttonbar.js
import React, { useContext, useState, useEffect, useReducer } from "react";
import { Context, filterReducer } from "../context";
const ButtonBar = () => {
const [state, setState] = useContext(Context);
const [filter, dispatch] = useReducer(filterReducer, state);
const showAll = () => {
dispatch({ type: "SHOW_ALL" });
console.log("showAll clicked");
};
const showApproval = () => {
dispatch({ type: "SHOW_APPROVAL" });
console.log("showApproval clicked");
};
return (
<div class="mb-2">
<button class="btn btn-primary btn-sm" name="all" onClick={showAll}>
All
</button>{" "}
<button
class="btn btn-primary btn-sm"
name="trump approval"
onClick={showApproval}
>
Trump Approval
</button>
</div>
);
};
export default ButtonBar;