Home > Blockchain >  How to set initialstate from user input inside the useState hook
How to set initialstate from user input inside the useState hook

Time:02-24

I am creating a timer and i want the timer to start ticking backwards based on the input value provided. I am confused on how to set the initialState in the useState hook instead of taking the default value as 0

Timer.js

 const Timer = () => {
const [input,setInput] = useState();
const inputHandler = (e) => {
    setInput(e.target.value);
}
    const [time,setTime] = useState(0);

    let timer;
    useEffect(()=>{
timer = setInterval(() => {
    if(time > 0){
        setTime(time-1);
    }
},1000)
return () => clearInterval(timer);
    },[])

  return (
   <>
   <h1>Timer</h1>
   <input value = {input} onChange = {inputHandler}/>
    <h1>{time}</h1>
   </>
  )
}

App.js

import './App.css';
import Timer from './components/Timer';

function App() {
  return (
    <div className="App">
     <Timer />
    </div>
  );
}

export default App;

CodePudding user response:

You can specify the type of your input and initialize it like that. Suppose it's a number and the initial value is 1:

const [input, setInput] = useState<number>(1);

CodePudding user response:

const Timer = () => {
  const [input, setInput] = useState(0)
  const [time, setTime] = useState(0)
  const inputHandler = (e) => {
    setTime(e.target.value)
    setInput(e.target.value)
  }

  let timer
  useEffect(() => {
    timer = setInterval(() => {
      if (time > 0) {
        setTime(time - 1)
        setInput(time - 1)
        console.log('1')
      }
    }, 1000)
    return () => clearInterval(timer)
  }, [input])

  return (
    <>
      <h1>Timer</h1>
      <input defaultValue={input} onChange={inputHandler} />
      <h1>{time}</h1>
    </>
  )
}

Use this code bro

  • Related