Issue
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>
);
}
Solution
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>
);
}
Answered By - Long Nguyen
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.