Very new to context and reducers in React. I am currently trying to use Context to get a date string from an event on a Line Graph. The line graph I'm using is from react-chartjs-2.
My context is setup and provided as below:
export const Context = createContext();
const initialState = {
isShowCarousel: false,
date: null,
coin: null
};
const reducer = (state, action) => {
switch (action.type) {
case "GRAPH_CLICKED":
return {
...state,
isShowCarousel: true,
date: action.payload.date,
coin: action.payload.coin
};
default:
return state;
}
};
export default function LandingPage(props) {
const classes = useStyles();
const [state, dispatch] = useReducer(reducer, initialState);
The provider is then setup like this:
<div className={classNames(classes.main, classes.mainRaised)}>
<Context.Provider
value={{
state,
dispatch
}}
>
<SectionCryptoPrices />
<NewsCarousel date={state.date} coin={state.coin} />
</Context.Provider>
</div>
My line graph component then imports the Context via the following:
import React, { useContext } from 'react';
import {Line} from 'react-chartjs-2';
import { Context } from "views/CryptoMashup/LandingPage";
function LineGraph (props) {
const dispatch = useContext(Context);
let coin = props.coin;
const state = {
labels: props.rowData.labels,
datasets: [
{
label: 'Price movement for ' + props.coin,
fill: true,
lineTension: 0.1,
backgroundColor: 'rgba(75,192,192,1)',
borderColor: 'rgba(0,0,0,1)',
borderWidth: 2,
data: props.rowData.prices
}
]
}
return (
// line graph
<div className="line-graph">
<Line
data={state}
options={{
legend:{
display:true,
position:'bottom'
},
onClick: function(evt, element) {
if(element.length > 0) {
let ind = element[0]._index;
let date = element[0]._xScale.ticks[ind];
let payload = {
date,
coin
}
dispatch({
type: "GRAPH_CLICKED",
payload: payload
})
}
}
}}
/>
</div>
);
}
export default LineGraph;
However I am getting the following: TypeError: dispatch is not a function
Any help on this would be hugely appreciated.