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

228
Visualizações
combine multiple useState of adding value into array into single function in react

This question is just related to reducing the code complexity. I have 8 arrays, in which I have to add items based on a button click. what I did is make 8 separate functions for all these tasks. is there any solution to combine all these functions into a single function that accepts an array as a parameter and does the rest of the job?

const [deleteArray,setDeleteArray]=useState([]);
const [newArray,setNewArray]=useState([]);
    const handleDeleteParking = (id) => {
        setDeleteArray((deleteArray) => [...deleteArray, id]);
}
   const handleNewParking = (id) => {
        setNewArray((newArray) => [...newArray, id]);
}

I have a total of 8 arrays with 8 separate functions to add items to the array, how can I achieve this task with a single function.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can't just pass the array into the function, since the array and the setArray function are different. But you can of course pass in the setter function instead:

const addToArray = (id, setStateFn) => {
    setStateFn((arr) => [...arr, id]);
}

// usage: instead of handleDeleteParking(id)
addToArray(id, setDeleteArray);
about 4 years ago · Juan Pablo Isaza Relatório

0

You could have created an object that will store all your values.

Check the below code that may help you.

const [data, setData] = useState({
   deleteParking: [],
   newParking: [],
});

const handleChange = (key, id) => {
   setData(prev => {
        return {
            ...prev,
            [key]: [
                ...prev[key],
                id,
            ]
        }
    });
}

handleChange('deleteParking', 1);
handleChange('newParking', 1);
about 4 years ago · Juan Pablo Isaza Relatório

0

You can merge all of your state into one state and then you can create common function to update particular state and then along with array (updated array) you can pass the property name. Like this:

const [arrState,setArrayState]=useState({deleteArr:[]});
const commonUpdateFunction=(id, propertyName)=>{
    setArrayState (prev=> ({...prev,[propertyName]:[...prev.[propertyName],id]}))
}

On click

const handleClick=(someId)=>{
    commonUpdateFunction(someId,deleteArr)
}
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