Skip to content

Commit

Permalink
Create ItemProvider w/ Docs
Browse files Browse the repository at this point in the history
  • Loading branch information
campb303 committed Feb 22, 2021
1 parent 748a49c commit 666135f
Show file tree
Hide file tree
Showing 3 changed files with 71 additions and 0 deletions.
29 changes: 29 additions & 0 deletions src/components/ItemProvider/ItemProvider.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import React, { useState, createContext, useContext, useEffect } from "react";

const ItemContext = createContext();
const ItemSetterContext = createContext();

export const useItem = () => useContext(ItemContext);
export const useItemSetter = () => useContext(ItemSetterContext);



export default function ItemProvider({ children }) {
const [item, setItem] = useState( {} );

useEffect( _ => console.log("Current Item is: ", item));

const setItemWrapper = (newItem) => {
console.log("Old Item: ", item);
setItem(newItem);
console.log("Set new item.");
}

return (
<ItemContext.Provider value={item}>
<ItemSetterContext.Provider value={setItemWrapper}>
{children}
</ItemSetterContext.Provider>
</ItemContext.Provider>
);
};
41 changes: 41 additions & 0 deletions src/components/ItemProvider/ItemProvider.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
Utility component that uses [React Contexts](https://reactjs.org/docs/context.html) [React Stateful Variables](https://reactjs.org/docs/hooks-state.html) to provide global access to the active item object.

Two functions are exported:

Function | Descrioption
- | -
`useItem` | Returns a reference to the state variable holding the current Item. Defaults to `false`.
`useItemSetter` | Returns a reference to the state variable update function.

For an in depth explanation of this pattern, see [this GitHub comment](https://github.itap.purdue.edu/ECN/webqueue2/issues/15#issuecomment-341).


## Usage
```jsx static
// App
<ItemProvider>
<SomeComponent />
</ItemProvider>
```

```jsx static
// SomeComponent
import { useEffect } from "react";
import { useItem, useItemSetter } from "ItemProvider";

const activeItem = useItem();
const setActiveItem = useItemSetter();

useEffect(
let item = someFuncToGetItem();
setActiveItem(item);
);

return(
{
item
? <p>{`${activeItem.queue} ${activeItem.number} was last updated ${activeItem.lastUpdated}.`}</p>
: <p>No item is currently loaded.</p>
}
);
```
1 change: 1 addition & 0 deletions src/components/ItemProvider/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export {default, useItem, useItemSetter } from "./ItemProvider";

0 comments on commit 666135f

Please sign in to comment.