Issue
when using fetch to post data in a react hook is it possible to infer that if loading is done, and there are no errors, data in not null?
type apiReturn<T> = {
data:T | null,
loading:boolean,
error?: Error
}
type message = {
msg:string
}
const apiPost = <T>(body:T):apiReturn<T> => {
const [state, setState] = useState<apiReturn<message>>({data:null,loading:true,error:undefined})
useEffect(()=>{
const httpCall = fetch(url,{...postrequest, body:body}).then((resp) => {
if (resp.parsedBody === undefined){
setState({ data:null,loading: false, error:new Error("Oops... Something went wrong!") });
}
setState({ data:response.parsedBody,loading: false });
},[fetch,setState])
return state
}
const usePost = (data:message) => {
const apiresponse = apiPost(data)
if(!apiresponse.loading && apiresponse.error === undefined)
//Possibly undefined, but should be defined as everything went okey
const test:message = apiresponse.data
}
Solution
You can use a discriminated union:
type ApiReturn<T> = {
loading: true,
} | {
loading: false,
error?: undefined,
data: T,
} | {
loading: false,
error: Error,
data?: null,
}
type message = {
text: string
}
const apiPost = <T extends object>(body: T): ApiReturn<T> => {
return null! // Implementation here
}
const usePost = (data: message) => {
const apiresponse = apiPost(data)
if (!apiresponse.loading && apiresponse.error === undefined) {
const test: message = apiresponse.data
}
}
Answered By – Titian Cernicova-Dragomir
Answer Checked By – David Marino (BugsFixing Volunteer)