-
-
Save mkrishnan-codes/3693adb5c28c227b3d86f1369b9acdd2 to your computer and use it in GitHub Desktop.
Fetching API data with React Hooks - Build a React App using Basic Hooks
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
const BookContextProvider = ({ children }) => { | |
// ... | |
// add | |
const getBooks = async () => { | |
const res = await fetch( | |
'https://jsonplaceholder.typicode.com/posts?_start=2&_limit=5' | |
); | |
const data = await res.json(); | |
setBooks([...books, ...data]); | |
}; | |
// ... | |
return ( | |
<BookContext.Provider value={{ books, getBooks, addBook, deleteBook }}> // add getBooks | |
{children} | |
</BookContext.Provider> | |
); | |
}; |
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 React, { useContext, useEffect } from 'react'; // add useEffect | |
// ... | |
const BookList = () => { | |
const { books, getBooks, deleteBook } = useContext(BookContext); // add getBooks | |
// add | |
useEffect(() => { | |
getBooks(); | |
}, []); | |
return ( | |
// ... | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment