Home > Blockchain >  React with TypeScript, prompt() return value
React with TypeScript, prompt() return value

Time:10-03

TypesScript shows an error when I want to update my State

TyepScript underlines in red the prompValue in setapiKey(prompValue); inside the getApiKey function, and the error is:

Argument of type 'string | null' is not assignable to parameter of type 'SetStateAction'. Type 'null' is not assignable to type 'SetStateAction'.ts(2345)

What is the problem how can I fix this?

function App() {

  const [apiKey, setapiKey] = useState('');

  const getApiKey = () => {
    const prompValue = prompt('Enter API Key');
    setapiKey(prompValue);
  }

  return (
    <div className="App">
      <h1>App</h1>
      <button onClick={getApiKey}>API</button>
      <p>{apiKey}</p>
    </div>
  );
}

CodePudding user response:

In fact, it's the powerful of typescript. prompt returns string | null.

You should handle the situation when the user cancels the prompt dialog to reduce mistakes.

function App() {

  const [apiKey, setapiKey] = useState('');

  const getApiKey = () => {
    const prompValue = prompt('Enter API Key');
    if(prompValue === null) {
      // do what ever you want when the user cancel the prompt
    }
    else {
      setapiKey(prompValue);
    }
  }

  return (
    <div className="App">
      <h1>App</h1>
      <button onClick={getApiKey}>API</button>
      <p>{apiKey}</p>
    </div>
  );
}

CodePudding user response:

As mentioned in the answers, the prompt return string (in case of user tried to write something) and null in case of user close the prompt without type anything on it.

So, Typescript will care about the promptValue. it assumes the type of your value is one of the string or null.

since the promptValue is a string there is no problem because you defined your apiKey value as a string which initialized in useState with an empty string.

But in the case of returning null from promptValue, typescript prevents you to put the null value into the apiKey which is defined as a string.

  • Related