Reputation: 43
I built this interface
export interface UserInfo {
success?: boolean,
user?: User,
employer?: Employer,
hr?: Hr
}
Now when I do this
let data = await loginUser(loginData);
console.log(data.success);
loginUser method code:
import {createApi, fetchBaseQuery} from "@reduxjs/toolkit/query/react";
import {BASE_API_ENDPOINT, LOGIN_API_ENDPOINT} from "../../constants/apis";
import {LoginData, UserInfo} from "../../models/apis/UserData";
export const loginApi = createApi({
reducerPath: 'loginReducer',
baseQuery: fetchBaseQuery({ baseUrl: BASE_API_ENDPOINT }),
endpoints: (builder) => ({
loginUser: builder.mutation<UserInfo, LoginData> ({
query: (data: LoginData) => ({
url: LOGIN_API_ENDPOINT,
method: "POST",
body: data
}),
transformResponse: (rawResult : UserInfo) => {
return rawResult
}
})
})
})
export const { useLoginUserMutation } = loginApi;
I get this error
Property 'success' does not exist on type '{ data: UserInfo; } | { error: FetchBaseQueryError | SerializedError; }'.
I am a newbie with typescript, and I want to access UserInfo object from { data: UserInfo; } but I am not being able to do so. Can anyone help?
Upvotes: 2
Views: 7190
Reputation: 1548
The actual issue is found inside the transformResponse
function, and how it 'tunnels' the response data further.
transformResponse: (rawResult : UserInfo) => {
return rawResult
}
rawResult
most likely is not of type UserInfo
, but a { data: UserInfo }
. And that's exactly what you see in the error you get.
So to fix it, the function should look like this:
transformResponse: (rawResult: { data: UserInfo }) => {
return rawResult.data
}
And then you code should work as expected, without any other if
s.
let data = await loginUser(loginData);
console.log(data.success);
Upvotes: 0
Reputation: 672
This happens because the property "success" exists only on type UserInfo. Since it's a union type the compiler can't be sure whether the function returns a data object (with UserInfo type) or an error object (FetchBaseQueryError | SerializedError)
In order to access the success property of the response, you can firstly check if it exists
if("success" in data){
console.log(data.success)
}
Read more about union types here:
https://www.typescriptlang.org/docs/handbook/unions-and-intersections.html
https://www.typescriptlang.org/docs/handbook/2/everyday-types.html#union-types
Upvotes: 5