0

I am trying to set two state variables when a user clicks an image, my browser thinks that I am calling a second function, how do I assign both of these variables? I know I can't use && but I don't know how to do it properly, sorry if this is a silly question.

<div className="img-wrap" key={doc.id}
                    onClick={() => (
                        setSelectedImg(doc.url) &&
                        setSelectedArtName(doc.artName))}
                >   
                    <img src={doc.url} alt={doc.artName} />
                    
                </div>
TSav
  • 5
  • 2

1 Answers1

3

A function with no explicit return statement returns undefined (a setter function like your setState).

In && the second condition is only checked if the first condition is truthy). Otherwise directly false is returned. Since the first function returns undefined(a falsy value), second setState will not run.

I think you can do without &&:

<div className="img-wrap" key={doc.id}
                    onClick={() => {
                        setSelectedImg(doc.url);
          setSelectedArtName(doc.artName)}}
                >   
                    <img src={doc.url} alt={doc.artName} />
                    
                </div>

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39
  • However my first setter does return correctly, what am I missing here since even the alt={doc.artName} in img tag below is populating correctly. – TSav Jul 14 '21 at 15:10
  • It does not matter. Your code does not throw an error. It just does not run the second setter. Your first setState runs very well but it returns undefined. After that your statement runs as you intend it to. Check console here to see what setState returns https://codesandbox.io/s/funny-darwin-2eso1?file=/src/App.js I created as a demo. – Tushar Shahi Jul 14 '21 at 15:14
  • That is because I am importing both of these setters from app.js and this is a component that I would like to dynamically update. I tried the suggestion below but now it throws "TypeError: setSelectedArtName is not a function" in the browser – TSav Jul 14 '21 at 15:17
  • So you are not importing it properly. You will have to show how you are passing this setter function. This further proves the point that setSelectedArtName was not run earlier. I hope you understand. – Tushar Shahi Jul 14 '21 at 15:19
  • Yes!! I got it, I forgot to pass this setter to the component in app.js.. thanks a lot for pointing me in the right direction! Much appreciated. – TSav Jul 14 '21 at 15:22