我试图制作一个钩子,对api进行两次查询,然后将结果保存为这样的状态:
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在useEffect中调用此函数如下:
useEffect(()=>{
updateApiInfo.GetApiIdeaInfo(CURRENT_AUTH_STATE,productId,CURRENT_LOGGED_IN_USER_NAME)
updateApiInfo.FetchProposalsForIdea(productId)
},[])
但问题是它只更新最后一个状态。它不会给出两个查询的结果。我在这里做错了什么?
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
}
})