Skip to content

Instantly share code, notes, and snippets.

@refayathaque
Created August 31, 2020 21:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save refayathaque/67e77ac5f4e3b5a6c905e56aa4d18358 to your computer and use it in GitHub Desktop.
Save refayathaque/67e77ac5f4e3b5a6c905e56aa4d18358 to your computer and use it in GitHub Desktop.
PostsContext.js
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