0

I'm getting a syntax error in when using React Hooks. Basically, I'm using an If statement inside useEffect and getting and Unexpected token error.

const [linkAnimation, setLinkAnimation] = useState();
const [isHovered, setIsHovered] = useState(true);

useEffect(() => {
    setLinkAnimation( 
      if(isHovered === true){  //getting unexpected token on this line
        console.log('true')
      }
    );
}, []); 

Syntax seems straight forward, but looks like I'm missing something.

See codepen

2
  • 1
    the syntax is wrong. see Expressions versus statements in JavaScript Commented Aug 16, 2019 at 17:19
  • 1
    setLinkAnimation is a function, and you are passing a if statement as an argument to the function. Error is expected. Commented Aug 16, 2019 at 17:21

2 Answers 2

3

The if statement is currently the parameter for your call to setLinkAnimation

I think you're actually trying to do something like this:

const [linkAnimation, setLinkAnimation] = useState();
const [isHovered, setIsHovered] = useState(true);

useEffect(() => {
  if(isHovered === true){  //getting unexpected token on this line
    console.log('true')
    setLinkAnimation(true);
  }
}, []); 
Sign up to request clarification or add additional context in comments.

Comments

2

Your setState function is expecting a value of some sort, but instead is just a function (console.log). If you wrap it in a fat arrow function with an implicit or explicit return, it works.

useEffect(() => {
    setLinkAnimation( () => {
      if(isHovered === true){
        console.log('true')
      }
    });
}, []); 

Edit: Please note that this will still not set the state, but it will at least complete your console.log.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.