Skip to content

Instantly share code, notes, and snippets.

@markodayan
Created August 5, 2020 10:51
Show Gist options
  • Save markodayan/e189625c5631eef2cb4dea03d83a375e to your computer and use it in GitHub Desktop.
Save markodayan/e189625c5631eef2cb4dea03d83a375e to your computer and use it in GitHub Desktop.
Automating Context Creation (Useful but Complex!)
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
);
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