简体   繁体   中英

How can I conditionally render this component based on whether or not there is data in localstorage?

I want MyList to render whatever is in localStorage (works great), however when there is nothing in local storage and I render the component, it renders empty. I would like to have a placeholder there for when that occurs. How can I best do that?

const MyList = ({setDrinks}) => {
    const setMyList = () => {
        let parsedData = JSON.parse(localStorage.getItem('favoriteDrinks'))
        setDrinks(parsedData)
    }

    return (
        <div>
            <button className="my-list" onClick={setMyList}>My List</button>
        </div>
    )
}

export default MyList

You can assign a random placeholder if your localStorage does not have data. Here's a minimal solution:

const MyList = ({setDrinks}) => {
    const setMyList = () => {
        const myDrinks = localStorage.getItem('favoriteDrinks');
        if (!myDrinks) {
            setDrinks({ message: "No drinks found!" });
            return;
        } 
        let parsedData = JSON.parse(myDrinks);
        setDrinks(parsedData);
    }

    return (
        <div>
            <button className="my-list" onClick={setMyList}>My List</button>
        </div>
    )
}

export default MyList 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM