Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

91
Vistas
React Redux issue delivering state value

I'm trying to show which values I choose from a select option of a component which has been populated previously using useSelector hook; ( not allowed to use React Select Library) My problem is first time I select it, I got an empty array returned; getting populated with first choosen value when is selected by second time. Every subsequent select, populate the array with the previous action value

Here is the related code:

const valueTemp = useSelector((state) => state.temperaments)

const [input, setInput] = useState({
    name: "",
    height_min: "",
    height_max: "",
    weight_min: "",
    weight_max: "",
    life_min: "",
    life_max: "",
    image: "",
    temperament: [],
 })

 var arrTemps=[];

  function showValues(){
    for(var i = 0; i < input.temperament.length; i++){
      for(var j=0; j < valueTemp.length;j++){
        if(parseInt(input.temperament[i])===valueTemp[j].id){
          arrTemps.push(valueTemp[j].name)
        }
      }
    }
    return arrTemps;
  }

var showMe="" ;
  function handleSelect(e){  
    setInput({
        ...input, temperament:[...input.temperament, e.target.value ]
    })  
    showMe=showValues() 
    console.log(showMe) 
    document.getElementById('mostrame').innerText=showMe;
  }
<select className={style.orderLarge} onChange={handleSelect}>
   <option value="">Temperaments:</option>
     {
       valueTemp.map((e) => (
         <option key={e.id} value={e.id}>{e.name}</option>              
       ))
     }
</select>
      
 <div id="mostrame"style={{color:'burlywood'}}>Temperamentos:</div>

I would greatly appreciate your help! Regards in advance!

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

I am not sure why you were doing all looping logics for. As far as I understood you just needed the history of your dropdown. I will add my version of your code.

Your select was an uncontrol element. I have added value on that so now react controls it. Your history History: {[...input.temperament]} is available after the select. The selected value is the last item in the array. Instead of document.getElementById('mostrame').innerText=showMe; you can directly use the last selected value like I have done. You are not recommended to access DOM elements like you are doing. Display your selected item name as as shown. Everything is working because I am converting the selected value into a NUMBER. When you select an item value returned is a string. You need to convert that to a number if you are using number. temperament: [...input.temperament, +e.target.value]. Adding + will convert a string to number.

import React, { useState } from 'react';

export default function App() {
  const valueTemp = [
    { id: 1, name: 'abc' },
    { id: 2, name: 'efg' },
    { id: 3, name: 'hij' }
  ];

  const [input, setInput] = useState({
    temperament: []
  });

  function handleSelect(e) {
    setInput({
      ...input,
      temperament: [...input.temperament, +e.target.value]
    });
  }

  return (
    <>
      <select
        onChange={handleSelect}
        value={input.temperament[input.temperament.length - 1]}
      >
        <option value="">Temperaments:</option>
        {valueTemp.map(e => (
          <option key={e.id} value={e.id}>
            {e.name}
          </option>
        ))}
      </select>
      <div>History: {[...input.temperament]}</div>
   <div>
    History Values: 
    {input.temperament.map(i => valueTemp.find(v => v.id === i)?.name+", 
     ")}
  </div>
  <div>Selected value =
  {
    valueTemp.find(
      v => v.id === input.temperament[input.temperament.length - 1]
    )?.name
  }</div>
    </>
  );
}
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda