Search code examples
react-nativeexpouuid

Configuring Math.random() in Expo


I am really sorry but I am making no headway with this. Working in expo on a basic react native shopping list and I need UUIDs for items. I'm using Math.random ()

const ID = Math.floor(Math.random() * 100);

and here is my list of items requiring IDs

const [items, setItems] = useState([
        { id: ID, text: "Milk" },
        { id: ID, text: "Eggs" },
        { id: ID, text: "Butter" },
        { id: ID, text: "Veggies" },
    ]);

I've tried every syntatic combination I can think of for const ID, so each error is not the same. I assume each time const ID is called the function should run and a different number should be returned.

Sorry to bother all but any help would be appreciated.

I hope this makes sense.

Thanks


Solution

  • Rather have function ID so that it generate different number each time.

    const ID = () => Math.floor(Math.random() * 100);
    
    const [items, setItems] = useState([
            { id: ID(), text: "Milk" },
            { id: ID(), text: "Eggs" },
            { id: ID(), text: "Butter" },
            { id: ID(), text: "Veggies" },
        ]);