Created
August 5, 2020 10:51
-
-
Save markodayan/e189625c5631eef2cb4dea03d83a375e to your computer and use it in GitHub Desktop.
Automating Context Creation (Useful but Complex!)
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, { createContext, useState, useReducer } from 'react'; | |
import createDataContext from './createDataContext'; | |
const initialState = []; | |
const blogReducer = (state, action) => { | |
switch (action.type) { | |
case 'ADD_BLOGPOST': | |
return [...state, { title: `Blog Post #${state.length + 1}` }]; | |
default: | |
return state; | |
} | |
}; | |
// Actions | |
const addBlogPost = (dispatch) => { | |
return () => { | |
dispatch({ type: 'ADD_BLOGPOST' }); | |
}; | |
}; | |
export const { Context, Provider } = createDataContext( | |
blogReducer, | |
{ addBlogPost }, | |
initialState | |
); |
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, { createContext, useReducer } from 'react'; | |
export default (reducer, actions, initialState) => { | |
const Context = createContext(); | |
const Provider = (props) => { | |
const [state, dispatch] = useReducer(reducer, initialState); | |
// actions === { addBlogPost: dispatch => { return () => {}}} | |
const boundActions = {}; | |
for (let key in actions) { | |
boundActions[key] = actions[key](dispatch); | |
} | |
return ( | |
<Context.Provider value={{ state, ...boundActions }}> | |
{props.children} | |
</Context.Provider> | |
); | |
}; | |
return { Context, Provider }; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment