Last active
July 31, 2019 23:38
-
-
Save AlexJWayne/ec102033b405e299f05568bf0614518d to your computer and use it in GitHub Desktop.
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, { useState, useEffect } from 'react' | |
import ItemList from './item-list' | |
export const CurrentItems = React.createContext([]) | |
const api = { | |
async getItems() { | |
return parseItemsOrWhatev(fetch('http://foo.com/items')) | |
} | |
} | |
export default function Root() { | |
// Store items from API in state. | |
const [items, setItems] = useState([]) | |
// Query the API. | |
useEffect(async () => { | |
const newItems = await api.getItems() | |
setItems(newItems) | |
}, []) | |
// the [] here ^ says to only run this on component mount, since | |
// no elements of that array will change between renders. | |
return ( | |
<CurrentItems.Provider value={items}> | |
<ItemList /> | |
</CurrentItems.Provider> | |
) | |
} |
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, { useContext } from 'react' | |
import { CurrentItems } from '/.' | |
export default function ItemList() { | |
const items = useContext(CurrentItems) | |
<ul> | |
{ items.map(item => <li>{item.name}</li> } | |
</ul> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment