Skip to content

Instantly share code, notes, and snippets.

@JeremyTheModernist
Last active July 1, 2020 17:38
Show Gist options
  • Save JeremyTheModernist/6e639964f69cb22dc300116133b04b1f to your computer and use it in GitHub Desktop.
Save JeremyTheModernist/6e639964f69cb22dc300116133b04b1f to your computer and use it in GitHub Desktop.
import React, { useState, createContext, useContext } from "react";
import { uuid } from "uuidv4";
var initialState = [
{
id: uuid(),
title: "Intro to HTML",
description: "Learn everything you need to know about html!",
duration: "1hr 5min",
},
{
id: uuid(),
title: "Python Basics",
description: "Finally obtain a foundation in Python Programming",
duration: "2hr 10min",
},
{
id: uuid(),
title: "Javascript and Beyond",
description: "Conquer vanilla JS and ES6 basics",
duration: "2hr 10min",
},
];
// the children should be of type ReactNode, which gives access many properties like defaultProps
type Props = {
children: React.ReactNode;
};
// define the type for the useState && Context input
// where represent "initial" and should be the initial state type
type IState = {
id: string;
title: string;
description: string;
duration: string;
}[];
// define the type for the context provider input where the first value represents the state and second one represents setState
// make an object so it's easier to work with in other components, auto-suggest
type ContextShape = {
state: IState | null;
setState: (props: IState) => void | IState;
};
// use ContextShape and undefined
// <> represent a generic and tell React what type the passed in value should be for this context
// var Store = createContext<ContextShape | undefined>(undefined);
var Store = createContext({} as ContextShape);
// Tell Store Provider that it should be of type React.FC ( functional component )
// This type has defaultProps
// can also use: React.FC<React.ReactNode> after component name, which is for children
export const StoreProvider = ({ children }: Props) => {
// useState expects a type of initial state or null
var [state, setState] = useState<IState | null>(initialState);
return (
<Store.Provider value={{ state, setState } as ContextShape}>
{children}
</Store.Provider>
);
};
export const useStore = () => useContext(Store);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment