Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

279
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!