Home > Enterprise >  Issue using Ternary operator in UseState
Issue using Ternary operator in UseState

Time:01-10

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?

CodePudding user response:

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.

CodePudding user response:

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: " ")
  •  Tags:  
  • Related