Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

84
Visualizações
Check for duplicate in array before adding to react state

I have a customInput with type select, it's onChange is running a setState.

my state object looks like this

const [upload, setUpload] = useState({
    uploadType: 'files',
    selectHeader: [],
    defaultFields: [
      {
        baseField: 'First name',
      },
      {
        baseField: 'Last name',
      },
      {
        baseField: 'Phone number',
      },
      {
        baseField: 'Company',
      },
      {
        baseField: 'Email',
      },
    ] 
  });

When the onChange runs, I am successfully adding a new object to the selectHeader array with a

{value: firstName, index: 1} 

The issue is that when a user selects a new value for a header at index 1 ( or any index for that matter) I want to check if there is duplicate in this array.

Im not sure how to do this inline with setState and cant seem to find a good thread on this example

Here is the CustomInput with type select below

<thead>
        <tr>
          {
            fileContacts.map((contact) => (
                <th scope="col" key={fileContacts.indexOf(contact)}>
        <WizardInput // this is just a fancy CustomInput at its core
        type="select"
        defaultValue={"Do not Import"}
        tag={CustomInput}
        name="selectHeader"
        id="selectHeader"
        onChange={({ target }) => {
          setUpload({...upload, selectHeader: [...upload.selectHeader, {value: target.value, index:fileContacts.indexOf(contact)}]})
          // this is adding a duplicate object if the user changes the header value twice.
        }}
        innerRef={register}
        errors={errors}
        options={['First Name', 'Last name', 'Phone', 'Email']}
      />
            </th>  
            ))}
        </tr>
      </thead>
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Create a new variable for the selectheader and filter that array for any duplicates (for any help check out this question How to remove all duplicates from an array of objects?) and then pass it into setUpload

about 4 years ago · Juan Pablo Isaza Relatório

0

Maybe you could filter out the previous one before adding in the new one.

setUpload({...upload, selectHeader: [...upload.selectHeader.filter(({value}) => value != target.value), { value: target.value, index:fileContacts.indexOf(contact) }] })
about 4 years ago · Juan Pablo Isaza Relatório

0

Try to use functional updates:

setUpload((upload)=>{

    if(upload.selectHeader.some(h => h.value == target.value)) return upload

    return {
        ...upload,
        selectHeader: [
            ...upload.selectHeader, 
            {
                value: target.value,
                index:fileContacts.indexOf(contact)
            }
        ]
    }
})
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda