Home > Blockchain >  setValue is not defined in react for react hooks
setValue is not defined in react for react hooks

Time:01-13

I'm getting an error saying the setValue portion of my code is not defined, but I did in the bottom portion of my main function. Not sure what's going on.

import React, {useState} from "react"; 

const updateAPI = () => {
  setValue("test"); 
}

export default function App() {
  const [value, setValue] = useState(""); 
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={updateAPI}></button>
      <p>{value}</p>
    </div>
  );
}

CodePudding user response:

Restructure code as below and try,

import React, {useState} from "react"; 

export default function App() {
  const updateAPI = () => {
    setValue("test"); 
  }

  const [value, setValue] = useState(""); 
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={updateAPI}>HI</button>
      <p>{value}</p>
    </div>
  );
}

CodePudding user response:

your updateAPI function cant find setValue useState hook because they are not in the same scope.

import React, {useState} from "react"; 


export default function App() {
   const [value, setValue] = useState(""); 

 const updateAPI = () => {
   setValue("test"); 
 }
 return (
   <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={updateAPI}></button>
      <p>{value}</p>
    </div>
 );
}
  •  Tags:  
  • Related