I am currently facing an issue with my React code where I am getting the error message:
The right-hand side of an 'in' expression must not be a primitive.
. I am unsure about how to resolve this problem effectively:
// The goal is to allow null, strings, objects, arrays, etc as potential responses from an API request
type APIGatewaySuccessResponse = unknown
...
const [data, setData] = useState<T>(null)
...
const fetchData = async () => {
onLoading()
const data = await sendRequest<T>(route, options)
// Simply checking if data is an object does not prevent the error....
if (typeof data === 'object' && 'error' in data) {
setError(data.error)
onError(data.error)
} else {
setData(data)
onSuccess(data)
}
...
Provided below is the sendRequest
code for better understanding:
// Function to make an API request
export const sendRequest = async <T extends APIGatewaySuccessResponse>(
route: string,
options?: FetchOptions
): Promise<T | APIGatewayErrorResponse> => {
const method = options?.method || FetchMethod.POST
const body = options?.payload ? JSON.stringify(options.payload) : null
const response = await fetch(route, {
method,
headers: {
...
},
body
})
const responseData = await response.json()
if (response.ok) {
return responseData as T
} else {
return responseData as APIGatewayErrorResponse
}
}
Since I am using generics, the in
function is causing this error. How can I handle this issue while still utilizing generics?