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

275
Visualizações
Issue using Ternary operator in UseState

I'm trying to do the following

    const[name,setName]=useState(recipe!==null?recipe.name:'')

The name appears to never be assigned with the ternary operator. Do they just not work within useState?

I've also tried reassigning the name like:

    if(recipe!==null){
         setName(recipe.name)

I receive an error in the console about too many re-renders. Is there any other way of assigning name conditionally?

Edit This is the structure of recipe

 const[recipes, setRecipes]=useState([
        {
            id:1,
            name:'Chicken Curry',
            ingredients:"Some ingredients",
            steps:"Some steps",
            energy:'2899',
            fat:'28.5',
            carbohydrates:'41.3',
            protein:'12',
            sodium:'1226',
            preparationTime:'15',
            difficulty:'Easy'
        }

How I'm calling the const

<RecipeModal recipe={activeRecipe}/>

and the recipe modal

const RecipeModal=({recipe}) =>{
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It's difficult to understand what is going on there but I will try to help. I guess that the recipe can be undefined instead of null. You could try below:

const [name, setName] = useState(recipe ? recipe.name : '');

In example above, we are simply checking if the recipe has a truthy value so the default state value will be an empty string if recipe is: null, undefined, 0 or "".


Regarding reassigning name state. Are you doing that inside a useEffect hook? Please review all your useEffect hooks to see if you are not changing a value that is present in a dependency array.

Infinite re-renders can be solved by adding an if statement to see if the value we want to assign to did really change. It could be also related to a place where you reassign a recipe. I could help further with a bit more code.

about 4 years ago · Juan Pablo Isaza Relatório

0

Try to use like this:

const[name,setName]=useState(recipe!==null?recipe.name:null)

Or if name is string type, then

const[name,setName]=useState(recipe!==null?recipe.name: " ")
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