Created
August 31, 2020 21:47
-
-
Save refayathaque/67e77ac5f4e3b5a6c905e56aa4d18358 to your computer and use it in GitHub Desktop.
PostsContext.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useReducer, createContext } from "react"; | |
export const PostsContext = createContext([ {}, () => {} ]); | |
const reducer = (state, action) => { | |
console.log(PostsContext) | |
switch (action.type) { | |
case 'FETCH_INIT': | |
return { ...state, isLoading: true, isError: false, request: action.payload }; | |
// destructuring statement keeps state object immutable, state is never directly mutated to maintain best practice | |
case 'FETCH_SUCCESS': | |
return { ...state, isLoading: false, isError: false, data: action.payload }; | |
case 'FETCH_FAILURE': | |
return { ...state, isLoading: false, isError: true, request: action.payload }; | |
default: | |
throw new Error(); | |
} | |
}; | |
const initialState = { isLoading: false, isError: false, request: null } | |
export const PostsContextProvider = props => { | |
const [ state, dispatch ] = useReducer(reducer, initialState); | |
return ( | |
<PostsContext.Provider value={[ state, dispatch ]}> | |
{ props.children } | |
</PostsContext.Provider> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment