I want to use state in switch as props
if page is board, I want to get postData and PostLoading. and then give it to pagePresenter. researchData and researchLoading are null.
below code show postData, postLoading, researchData, researchLoading is not defined.
export default ({
match: {
params: { code, page },
},
}) => {
switch(page){
case "board":
const { data: postData, loading: postLoading } = useQuery(ALL_POST, {
variables: { code },
fetchPolicy: "network-only",
});
const onPostClick = (id, code) => {
history.push(`/article/${code}/${id}`);
};
break;
case "research":
const { data: researchData, loading: researchLoading } = useQuery(
ALL_RESEARCH,
{
variables: { code },
}
);
break;
default:
return null;
}
return (
<PagePresenter
type={page}
postLoading={postLoading ? postLoading : null}
postData={postData ? postData : null}
researchLoading={researchLoading ? researchLoading : null}
researchData={researchData ? researchData : null}
/>
)
}
CodePudding user response:
I suspect that since you're declaring const { data: postData, loading: postLoading }
inside the context of the switch
, it'll be undefined outside of this context. Just like declaring a variable inside function. I suggest you take advantage of the useState
hook. Simply initialise a blank state outside the switch
and set it to postData
after the postData
is fetched.
So somewhere outside your switch
do const [postDataState, setPostData] = useState(undefined)
and then after you have your postData
, do setPostData(postData)
.
And finally, pass postDataState
as props to your component. So instead of postData={postData ? postData : null}
you'd say postData={postDataState ? postDataState : null}
Don't forget to import {useState} from 'react'