Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 58 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
"@material-ui/styles": "^4.3.0",
"@material-ui/system": "^4.3.2",
"@rematch/core": "*",
"@tanstack/react-query": "^5.85.5",
"@testing-library/jest-dom": "^5.14.1",
"@testing-library/react": "^12.0.0",
"@testing-library/user-event": "^13.2.1",
Expand Down
12 changes: 11 additions & 1 deletion src/components/Home/Home.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, { useState, useEffect, useContext } from 'react';

import { useQueryClient } from '@tanstack/react-query';
import api from '../../api/treeTrackerApi';
import FilterListIcon from '@material-ui/icons/FilterList';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
Expand Down Expand Up @@ -71,6 +72,15 @@ function Home(props) {
}
loadUpdateTime();
}, []);
const queryClient = useQueryClient();
useEffect(() => {
queryClient.prefetchQuery({
queryKey: ['species'],
queryFn: () => api.getSpecies(),
staleTime: 1000 * 60 * 5, // cache for 5 mins
refetchOnWindowFocus: false,
});
}, [queryClient]);

const timeRange = [
{ range: 30, text: 'Last Month' },
Expand Down
93 changes: 34 additions & 59 deletions src/context/SpeciesContext.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import React, { useState, useEffect, createContext } from 'react';
import React, { useState, createContext } from 'react';
import api from '../api/treeTrackerApi';
import * as loglevel from 'loglevel';
import { useQuery, useQueryClient } from '@tanstack/react-query';

const log = loglevel.getLogger('../context/SpeciesContext');

Expand All @@ -9,7 +10,6 @@ export const SpeciesContext = createContext({
speciesList: [],
speciesInput: '',
setSpeciesInput: () => {},
loadSpeciesList: () => {},
onChange: () => {},
isNewSpecies: () => {},
createSpecies: () => {},
Expand All @@ -19,98 +19,74 @@ export const SpeciesContext = createContext({
combineSpecies: () => {},
});

export function SpeciesProvider(props) {
const [speciesList, setSpeciesList] = useState([]);
const [speciesInput, setSpeciesInput] = useState(''); // only used by Species dropdown and Verify
const [isLoading, setIsLoading] = useState(false);
export function SpeciesProvider({ children }) {
const [speciesInput, setSpeciesInput] = useState('');
const queryClient = useQueryClient();

useEffect(() => {
const abortController = new AbortController();
loadSpeciesList({ signal: abortController.signal });
return () => abortController.abort();
}, []);

// EVENT HANDLERS

const loadSpeciesList = async (abortController) => {
setIsLoading(true);
const species = await api.getSpecies(abortController);
setSpeciesList(species);
setIsLoading(false);
};
const { data: speciesList = [], isLoading, refetch } = useQuery({
queryKey: ['species'],
queryFn: () => api.getSpecies(),
staleTime: 1000 * 60 * 5,
refetchOnWindowFocus: false,
enabled: false, // don’t auto-fetch, rely on Home preload
});

// only used by Species dropdown
const onChange = async (text) => {
const onChange = (text) => {
console.log('on change:"', text, '"');
setSpeciesInput(text);

// ✅ Fallback: if species list is empty (not prefetched yet), trigger fetch
if (!speciesList.length) {
refetch();
}
};

// only used by Verify
const isNewSpecies = () => {
//check input is valid and doesn't already exist
if (!speciesInput) {
log.debug('empty species, false');
return false;
}
log.debug(
'to find species %s in list:%d',
speciesInput,
speciesList.length
);
if (!speciesInput) return false;
return speciesList.every(
(c) => c.name.toLowerCase() !== speciesInput.toLowerCase()
);
};

const createSpecies = async (payload) => {
const species = await api.createSpecies(
payload || {
name: speciesInput,
desc: '',
}
payload || { name: speciesInput, desc: '' }
);
console.debug('created new species:', species);
setSpeciesList([species, ...speciesList]);
// update cache
queryClient.setQueryData(['species'], (old = []) => [species, ...old]);
};

//to get the species id according the current speciesInput
const getSpeciesId = () => {
if (speciesInput) {
return speciesList.reduce((a, c) => {
if (a) {
return a;
} else if (c.name === speciesInput) {
return c.id;
} else {
return a;
}
}, undefined);
return speciesList.find((c) => c.name === speciesInput)?.id;
}
};

const editSpecies = async (payload) => {
const { id, name, desc } = payload;
const editSpecies = async ({ id, name, desc }) => {
const editedSpecies = await api.editSpecies(id, name, desc);
console.debug('edit old species:', editedSpecies);
// refetch species list after editing
queryClient.invalidateQueries(['species']);
};

const deleteSpecies = async (payload) => {
const { id } = payload;
const deletedSpecies = await api.deleteSpecies(id);
console.debug('delete outdated species:', id, deletedSpecies);
const deleteSpecies = async ({ id }) => {
await api.deleteSpecies(id);
console.debug('delete outdated species:', id);
queryClient.invalidateQueries(['species']);
};

const combineSpecies = async (payload) => {
const { combine, name, desc } = payload;
const combineSpecies = async ({ combine, name, desc }) => {
await api.combineSpecies(combine, name, desc);
queryClient.invalidateQueries(['species']);
};

const value = {
isLoading,
speciesList,
speciesInput,
setSpeciesInput,
loadSpeciesList,
onChange,
isNewSpecies,
createSpecies,
Expand All @@ -119,9 +95,8 @@ export function SpeciesProvider(props) {
deleteSpecies,
combineSpecies,
};

return (
<SpeciesContext.Provider value={value}>
{props.children}
</SpeciesContext.Provider>
<SpeciesContext.Provider value={value}>{children}</SpeciesContext.Provider>
);
}
10 changes: 9 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,12 @@ import App from './App';
import 'typeface-roboto';
import './index.css';

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

ReactDOM.createRoot(document.getElementById('root')).render(
<QueryClientProvider client={queryClient}>
<App />
</QueryClientProvider>
);
Loading
Loading