Skip to content

Instantly share code, notes, and snippets.

@feliperodriguess
Created June 12, 2021 05:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save feliperodriguess/eef96e8e66aa857808d2929f8a92c8ca to your computer and use it in GitHub Desktop.
Save feliperodriguess/eef96e8e66aa857808d2929f8a92c8ca to your computer and use it in GitHub Desktop.
import { useState, useEffect, useContext, createContext } from 'react'
import axios from 'axios'
const FetchContext = createContext()
const url = 'https://jsonplaceholder.typicode.com/posts'
const FetchProvider = ({ children }) => {
const [posts, setPosts] = useState([])
const providerValue = useMemo(
() => ({
posts,
setPosts,
}),
[]
)
useEffect(() => {
;(async () => {
const { data } = await axios.get(url)
setPosts(data)
})()
}, [])
return <FetchContext.Provider value={providerValue}>{children}</FetchContext.Provider>
}
const useFetch = () => {
return useContext(FetchContext)
}
export { FetchProvider, useFetch }
//Wrap index.js w/ <FetchProvider> ... </FetchProvider>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment