In my React application, I need to return from a custom hook some data and functions. The hook data should be only returned if a condition is valid.
The custom hook is used like this:
const {
conversation,
currentMember,
handleAddMessage,
handleResolveConversation,
} = useConversation(consentee);
The idea is that in pseudo-code:
if (valid_condition)
// give back the things from the hook
const {
conversation, => DATA
currentMember, => DATA
handleAddMessage, => FUNCTION
handleResolveConversation, => FUNCTION
} = useConversation(consented);
else
give back the CONSENTEE
and
the rest should be NULL
The problem is I need to call this hook if the valid condition is met and not sure how to make it so and return what I need to be used.
The second issue is for conversation and currentMemebr which need to return nothing to not trigger some other stuff related but I have that consentee parameter which I need to return only as data if the hook is not called.
Please ask in comments if make too much confusion on my question :)
As a reference, I'm adding the custom hook
const useConversation = consentee => {
const { user } = useAuth();
const { joinConversation, joinedConversation } = useJoinConversation();
const resolveConversation = useResolveConversation();
const addMessage = useAddMessage();
const conversation = useGetConversation(joinedConversation?.conversation?.id);
const currentMember = useMemo(() => joinedConversation?.member, [
joinedConversation,
]);
useEffect(() => {
if (consentee) {
const input = {
originId: consentee?.id,
originType: conversationOriginTypes.consentee,
memberId: user.id,
name: `${user.firstName} ${user.lastName}`,
memberType: messageAuthorTypes.user,
};
joinConversation(input);
}
}, [consentee, joinConversation, user]);
const handleAddMessage = useCallback(
async message => {
const content = trimWhitespace(message);
const input = {
conversationId: joinedConversation?.conversation?.id,
memberId: currentMember.id,
content,
};
await addMessage(input);
},
[joinedConversation, addMessage, currentMember],
);
const handleResolveConversation = useCallback(async () => {
await resolveConversation(joinedConversation?.conversation?.id);
}, [resolveConversation, joinedConversation]);
return {
conversation,
currentMember,
handleAddMessage,
handleResolveConversation,
};
};
export default useConversation;