Created
August 9, 2020 16:54
-
-
Save kyds3k/26d72d7ed9a8f9c93bcd0e35cbc12544 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 React from 'react'; | |
import { createContext, useState, useEffect } from 'react'; | |
export const WatchListContext = createContext(); | |
export const WatchListContextProvider = props => { | |
//check to see if the watchList exists in local storage, if not return null | |
const localList = () => { | |
if (localStorage.getItem('watchList')) { | |
return localStorage.getItem('watchList').split(','); | |
} | |
return null; | |
}; | |
const [watchList, setWatchList] = useState( | |
localList() || ['bitcoin', 'ethereum', 'ripple', 'litecoin'] | |
); | |
useEffect(() => { | |
localStorage.setItem('watchList', watchList); | |
}, [watchList]); | |
const deleteCoin = coin => { | |
setWatchList( | |
watchList.filter(el => { | |
return el !== coin; | |
}) | |
); | |
}; | |
const addCoin = coin => { | |
if (watchList.indexOf(coin === -1)) { | |
setWatchList([...watchList, coin]); | |
} | |
}; | |
return ( | |
<WatchListContext.Provider value={{ watchList, deleteCoin, addCoin }}> | |
{props.children} | |
</WatchListContext.Provider> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment