-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstore.js
47 lines (38 loc) · 1.08 KB
/
store.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import React, { createContext, useReducer, useContext, useEffect } from "react";
import { useRouter } from "next/router";
export const TOGGLE = "TOGGLE";
export const CLEAR = "REMOVE";
const reducer = (state, action) => {
switch (action.type) {
case TOGGLE:
return {
...state,
selectedTags: state.selectedTags.includes(action.payload)
? state.selectedTags.filter((i) => i !== action.payload)
: [...state.selectedTags, action.payload],
};
case CLEAR:
return {
...state,
selectedTags: [],
};
default:
return state;
}
};
const initialState = {
selectedTags: [],
};
export const Context = createContext(initialState);
const StoreProvider = ({ children }) => {
const [state, dispatch] = useReducer(reducer, initialState);
const { locale } = useRouter();
useEffect(() => {
dispatch({ type: CLEAR });
}, [locale]);
return (
<Context.Provider value={[state, dispatch]}>{children}</Context.Provider>
);
};
export default StoreProvider;
export const useStore = () => useContext(Context);