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

136
Visualizações
useEffect hook not getting called on prop changes

I have 2 dropdowns, I need to update the values of the second dropdown based on the first. On page load, I need to initialize the dropdown values based on conditions, like so:

    const getInitialState= () => {
            //defaultSelected has a value if saved in DB, if not then I set the 0 option value in type, based on this value option value will be populated in the dropdown. I get all the values from parent component
            let updatedType= defaultSelected !== ""
        ? defaultType
        : Region.RegionType;
        console.log('typeeeee', type)
        return updatedType;
            }
        
              useEffect(() =>{
    //Here in options dropdown values object is set based on type selected 
               let updatedOptions = !_.isEmpty (type)
              ? "a" //value from db if save
              : "b"; //If not 0th value of the object
        
              setOptions(prevOptions => ({
                ...prevOptions,
                ["options"]: updatedOptions 
              }));
          },[type]);
        
          const [type, setType] = useState(getInitialState);
          const [options, setOptions] = useState('');

          const changeCrTypeHandler = (event) =>{
        const { name, value } = event.target;
        setType(type =>({
          ...type,
          [name]: value}));
      }

return (
    <>
          <select
            onChange={changeCrTypeHandler}
            style={{ width: "150px" }}
            value={!_.isEmpty(type)}
            name= "type"
          >
            {_.map(customMap, (crId) => { //I get this cusomMap from Parent component
              return (
                <option
                  id={crId.customType}
                  value={crId.customType}
                  key={crId.customType}
                >
                  {crId.customType}
                </option>
              );
            })}
          </select>{" "}
          &nbsp; &nbsp;&nbsp; &nbsp;
          <select
            onChange={changeCrHashHandler} //second dropdown onchange
            style={{ width: "250px" }}
            value={crHashId}
            name= "options"
          >
            {_.map(!_.isEmpty(options), (o) => { //This options are created based on type, which is currently not getting set
              return (
                <option
                  id={o.customId}
                  value={o.customId}
                  key={o.customId}
                >
                  {o.name}
                </option>
              );
            })}
          </select>

Based on type value then I need to set the value of the option.

But my useEffect hook doesn't get called upon changes in type. How can I call the useEffect method whenever there is any changes in the type?

Any help for this would be much appreciated.

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

0

You are calling setState before it is defined. For the initial value, you just return it without calling setState. For having the second dropdown state depending on the first one's state, you could use the useEffect hook, like so:

const [firstDropdown, setFirstDropdown] = useState(getInitialState({type:"", options:""}));
const [secondDropdown, setScondDropdown] = useState(0); // you could use whatever initial value you want here
const getInitialState= () => {
  //some logic to get the value in type
  //just return that inital value without calling setState
  
}
// the function inside useEffect runs every time firstDropdown changes
useEffect(()=>{
  // some logic on firstDropdown
  let value = firstDropdown+25
  setScondDropdown(value)
},[firstDropdown]);

Update:

In your useEffect, change this :

 setOptions(prevOptions => ({
                ...prevOptions,
                ["options"]: updatedOptions 
              }));

to this :

 setOptions(updatedOptions)
about 4 years ago · Juan Pablo Isaza Relatório

0

Use the useState as below:

const [state, setState] = useState({})
setState((prev) => {
    // do whatever you want to do with the previous state
})

And for the name, please do not use setState as your setter function of useState. because setState is another method in the class based components in React

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