'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


Solution 1:[1]

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 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ShubhankarKG