Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, { createContext, useState } from 'react';
- import uuid from 'uuid/v1';
- export const BookContext = createContext();
- export const BookContextProvider = props => {
- const [books, setBooks] = useState([]);
- const addBook = async (title, author) => {
- const booksData = await localStorage.getItem('books');
- if(booksData) {
- setBooks([...JSON.parse(booksData), { title, author, id: uuid()}]);
- localStorage.setItem('books', JSON.stringify(books));
- } else {
- setBooks([...books, { title, author, id: uuid()}]);
- localStorage.setItem('books', JSON.stringify(books));
- }
- };
- const removeBook = async id => {
- let filteredBooks = books.filter(book => book.id !== id);
- await setBooks([...filteredBooks]);
- localStorage.setItem('books', JSON.stringify(books));
- };
- return (
- <BookContext.Provider value={{ books, addBook, removeBook }}>
- { props.children }
- </BookContext.Provider>
- );
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement