Reputation: 1223
import React, {
FunctionComponent,
useState,
useEffect
} from 'react'
const SearchBar: FunctionComponent = () => {
const [searchValue, setSearchValue] = useState < string > ('')
const [isSuggestionOpen, setIsSuggestionOpen] = useState < boolean > (false)
async function showSuggestedWords(event) {
setSearchValue(event.target.value)
try {
const res = await fetch(`https://www.someurl.com/q=${searchValue}`)
const suggestedWordsArray = await res.json()
// setSuggestedWords(suggestedWordsArray[1].slice(0, 10))
setIsSuggestionOpen(true)
return
} catch {
console.log('error fetching suggested results')
setIsSuggestionOpen(false)
}
}
return ( <
div >
<
form action = "/Controller"
method = "get" >
<
input name = "q"
type = "text"
value = {
searchValue
}
onChange = {
showSuggestedWords
}
autoComplete = "off"
autoCapitalize = "off"
autoCorrect = "off"
spellCheck = "false"
placeholder = "Search here" /
>
<
button type = "submit" >
Submit <
/button> <
/form> <
/div>
)
}
ReactDOM.render( <
div > < h1 > Hello, world! < /h1> <SearchBar / > < /div>,
document.getElementById('root')
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/typescript/4.0.3/typescript.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>
I'm new to typescript so it might be a obvious solution.
I have a project made with React, Nextjs and Typescript.
I use typescript to define my state type like so:
const [searchValue, setSearchValue] = useState<string>('')
And I get an error at runtime:
ReferenceError: string is not defined
.
I can't figured out what's wrong. Everywhere i check they suggest to define state type like i did above.
Here are my typescript config:
{
"compilerOptions": {
"target": "es5",
"lib": [
"dom",
"dom.iterable",
"esnext"
],
"allowJs": true,
"skipLibCheck": true,
"strict": false,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"noImplicitAny": true,
"allowSyntheticDefaultImports": true
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx"
],
"exclude": [
"node_modules"
]
}
I don't have webpack config because they are shipped with Nextjs (which is already configured to work with typescript.)
I do have @types/react @types/react-dom @types/node
installed.
Any hint?
Upvotes: 2
Views: 3309
Reputation: 1223
It turned out it was some mismatching configuration in my babel.config.json
I removed everything and kept just those lines:
{
"presets": ["next/babel"],
"env": {
"test": {
"presets": ["next/babel"]
}
}
}
In this way I still can run my Jest tests.
Hopefully it can be helpful for someone else in this situation :)
Upvotes: 2