Reputation: 885
I can't seem to fix some typescript error I get on my react app.
Code:
const [fetchJobTitlesCall, { data }] = useLazyQuery<Jobtitles, JobtitlesVariables>(JobTitlesQuery)
useEffect(() => {
fetchJobTitlesCall({ variables: { keyword: 'Dev' } })
}, [fetchJobTitlesCall, data])
return (
<Autocomplete
onChange={(event, value) => dispatchJobTitlesFilter(value)}
multiple
id="tags-outlined"
options={data?.jobTitles} // this line throwing error
getOptionLabel={option => option.name + ` (${option.totalApplicants})`} // this line throwing error
filterSelectedOptions
renderInput={params => (
<TextField
{...params}
onChange={event => fetchJobTitles(event.target.value)}
variant="outlined"
label="Search Job Title"
placeholder="Search Job Title"
/>
)}
/>
)
Error:
Type 'Jobtitles_jobTitles | undefined' is not assignable to type 'unknown[]'. Type 'undefined' is not assignable to type 'unknown[]'.
Any idea how to fix this?
Upvotes: 1
Views: 305
Reputation: 14221
The options
property on the Autocomplete
component is expecting the prop to be of type unknown[]
. You need to handle the case where data?.jobTitles
is undefined
. You should be able to just default it to an empty array if the value is undefined.
options={data?.jobTitles || []}
Upvotes: 1
Reputation: 191749
Without seeing the type definition of Autocomplete
it's difficult to tell exactly, but it looks like the options
property requires an array (of unknown type). For example:
type Options = unknown[];
This requires it to always be an array, even an empty array. The following code will not work:
let options: Options;
const data = { jobTitles: undefined };
options = data.jobTitles; // same error
You can resolve this by defaulting to an empty array in case jobTitles
is not known, for example:
options={data?.jobTitles || []}
This behavior may be undefined, though -- you might have to refer to the Autocomplete library itself to see how to handle this properly.
Upvotes: 1