I am trying to create a simple component that returns all my organizations from Apollo GraphQL server (query). I want to render all these orgs from a context state where it could be placed with a dispatch method after the component is mounted (handled by useEffect hook).
useEffect hook should call function getOrganizations and then call custom hook useGetOrganizations if a state result (organizations array) is empty. useGetOrganisations hook uses useQuery from @apollo/react-hooks.
Unfortunately, this is not working and my console says that "./src/components/Organisations/Organisations.js Line 32:13: React Hook "useGetOrganisations" is called in function "getOrganisations" which is neither a React function component or a custom React Hook function react-hooks/rules-of-hooks"
Please, can you help me?
import React, { useEffect } from 'react';
import { useQuery } from '@apollo/react-hooks';
import ORGANIZATIONS_QUERY from './OrganizationsGraphql';
import { Store } from '../../store/Store';
const Organizations = props => {
const { state, dispatch } = React.useContext(Store);
useEffect(() => {
getOrganizations();
});
const useGetOrganisations = async () => {
const { data, loading, error } = useQuery(ORGANISATIONS_QUERY);
if (loading) {
return 'Loading...';
}
if (error) {
return `Error! ${error.message}`;
}
return dispatch({
type: 'FETCH_ORGANISATIONS',
payload: data.organizations,
});
};
const getOrganizations = () => {
if (state.organizations.length === 0) {
useGetOrganizations();
}
};
return (
<div>
<h1>All organisations</h1>
{console.log(state.organizations)}
</div>
);
};
export default Organizations;