Home > Software design >  How do you make sure no two items have the same ID in an Array?
How do you make sure no two items have the same ID in an Array?

Time:11-09

I have an array that stores the ID and Placeholder title of a new component every time the button "Create a list" is clicked. I am trying to make sure that there are no duplicated ID's. Essentially I just want check that the ID doesn't already exist, and if it does; to create a new one.

My code is below:

ElementContext.js:

import React, { createContext, useState } from 'react';
import Todobox from './components/Todobox';

export const ElementContext = createContext();

export const ElementContextProvider = ({children}) => {
    const [elements, setElements] = useState([]);
    const [elementId, setElementId] = useState(1);

    const newElementId = (elements) =>{
        const newId = Math.floor(Math.random()*100).toString();
        setElementId(newId)
    }

    const newElement = () =>{
        newElementId();
        setElements((prev) => [...prev, {title: 'Placeholder', id:elementId}])
        console.log(elements)
    };

    const value = {
        elements,
        setElements,
        newElement,
        newElementId,
        elementId
    };

    return(
        <ElementContext.Provider value={value}>
            {children}
        </ElementContext.Provider>
    )
};

HomePage.jsx:

import react from 'react';
import { useContext } from 'react';
import '../App.css';
import Todobox from './Todobox';
import { ElementContext } from '../ElementContext';

export default function HomePage(){
    const { elements, setElements, newElement, elementsId } = useContext(ElementContext);


    return(
        <div className='page-container'>
        <div className='header'>
          <a className='header-title'>Trello Clone!</a>
          <a className='header-button' onClick={newElement}>Create a list</a>
        </div>
      <div className='element-field'>
        {elements.length !== 0 &&
          elements.map((elements, newElementId) => <Todobox key={newElementId} />)}
      </div>
    </div>
    )
}

CodePudding user response:

Idea:

You need to implement a state that holds an object const [refDict, setRefDict] = useState({}); that stores the key as elementId and value as true. So when you want to insert a new element need to check whether the state already has this key or not. if the state has the key it means elementId is not unique so no need to push to setElements() and vice versa.

Declare a new state as:

const [refDict, setRefDict] = useState({});

and inside your newElement() add logics like this:

const newElement = () => {
  newElementId();
  if (!refDict[elementId]) { //so if nothing in "refDict" that means the elementId is unique
    setElements(prev => [...prev, { title: 'Placeholder', id: elementId }]);
    setRefDict((prev) => ({...prev, [elementId]: true}));
  }
  console.log(elements);
};

You can also play around with this sandbox

CodePudding user response:

you need increments your array

setElementId(elementId   1)

you only need this. more then this, is not necessary. but, filter is one option.

  • Related