Im trying to make a hook that do two queries to api and then save the result in the state like this:
const useQueryApiInfo = ():UseQueryType=>{
const [state, setState] = useState<stateType>({data:null, error:null, loading:false})
const CURRENT_LOGGED_IN_USER_NAME = getLoggedInUserName();
// for getApiIdeaInfo query
const GetApiIdeaInfo:GetApiIdeaInfoType =async(authState, id, CURRENT_LOGGED_IN_USER_NAME)=>{
const res = await getApiIdeaInfo(authState, id, CURRENT_LOGGED_IN_USER_NAME)
if (res.errors) { setState({ ...state, error: res.errors, loading: false, data: null }) }
if (!res.data) return;
setState({ data:{...state.data?.resFromFetchProposal,resFromApiInfo:res.data.getApiIdeaFullInfo}, error:null, loading:false})
console.log(state,"from getIdea")
}
// for fetchProposal mutation
const FetchProposalsForIdea =async(id:string)=>{
const res = await fetchProposalsForIdea(id)
if (res.errors) { setState({ ...state, error: res.errors, loading: false, data: null }) }
if (!res.data) return;
setState({ data:{...state.data?.resFromApiInfo, resFromFetchProposal:res.data?.fetchProposalsForAnIdea}, error:null, loading:false})
}
return [state, {GetApiIdeaInfo, FetchProposalsForIdea, ReactOnApiIdea}]
}
iam calling this function in useEffect like this:
useEffect(()=>{
updateApiInfo.GetApiIdeaInfo(CURRENT_AUTH_STATE,productId,CURRENT_LOGGED_IN_USER_NAME)
updateApiInfo.FetchProposalsForIdea(productId)
},[])
but the problem is It is updating only the last state. it is not giving the result of both queries. what Iam doing wrong here?
setState((prevState) => {
return {
...prevState,
data: {
...prevState.data,
resFromFetchProposal: res.data?.fetchProposalsForAnIdea
},
error:null, loading:false
}
})
setState((prevState) => {
return {
...prevState,
data: {
...prevState.data,
resFromApiInfo: res.data?.getApiIdeaFullInfo
},
error:null, loading:false
}
})