JLB
JLB

Reputation: 29

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

Upvotes: 1

Views: 371

Answers (1)

ShubhankarKG
ShubhankarKG

Reputation: 172

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 

Upvotes: 2

Related Questions