Skip to content

Instantly share code, notes, and snippets.

@AlexJWayne
Last active July 31, 2019 23:38
Show Gist options
  • Save AlexJWayne/ec102033b405e299f05568bf0614518d to your computer and use it in GitHub Desktop.
Save AlexJWayne/ec102033b405e299f05568bf0614518d to your computer and use it in GitHub Desktop.
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>
)
}
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