Created
June 12, 2021 05:34
-
-
Save feliperodriguess/eef96e8e66aa857808d2929f8a92c8ca to your computer and use it in GitHub Desktop.
This file contains 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 { 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