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

276
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 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