Home > Software engineering >  React, I want to print out an object in a function
React, I want to print out an object in a function

Time:03-15

I want the 'percent' to decrease by 0.25 every second after pressing the Start button.

but 'percent' is output as 'object Object'.

import React, {useState, useRef, useCallback} from 'react';

const App = () => {
    const [percent,setPercent] = useState(1);
    const intervalRef = useRef(null);

    const start = useCallback(() =>{
        if (intervalRef.current !== null){
          return;
        }
        intervalRef.current = setInterval(()=>{
          if (percent > 0){ 
            setPercent(c => c - 0.25);
            console.log("percent = "   {percent});
      
          }
          else {
            setPercent(c => 1);
          }
        }, 1000);
    
      }, []);

      return (
          <div>
              <button onClick={()=>{start()}} />
          </div>
      );
}

CodePudding user response:

Is your problem is only the fact that it print 'object Object', this happens because you are using operator between a string and an object, and this converts an object into a string, resulting into the string 'object Object'.

To print the object the way you want, you should use but pass it as a second parameter to console.log

console.log("percent = ", { percent });
  • Related