Skip to content

Commit

Permalink
Refactor: code for loading JSON files
Browse files Browse the repository at this point in the history
Got this warning from Vite:

> [vite] warning: invalid import "./${listName}.json". Variable
> imports cannot import their own directory, place imports in a separate
> directory or make the import filename more specific. For example:
> import(`./foo/${bar}.js`).

...though I'm not sure why since it seemed to work fine anyway.

This feels better in any case: only one file loading the default word
list.
  • Loading branch information
dgmstuart committed Apr 19, 2024
1 parent 4460644 commit 23178be
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 16 deletions.
14 changes: 0 additions & 14 deletions src/data/loader.ts

This file was deleted.

19 changes: 19 additions & 0 deletions src/lib/JsonDataImporter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
export default class JsonDataImporter<T> {
#defaultData: T;

constructor({ defaultData }: { defaultData: T }) {
this.#defaultData = defaultData;
}

async import(listName: string): Promise<T> {
let data = this.#defaultData;

try {
data = (await import(`../data/${listName}.json`)).default;
} catch (error) {
console.error("Failed to load the data", error);
}

return data;
}
}
5 changes: 3 additions & 2 deletions src/loaders/wordListLoaders.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import defaultWordList from "../data/teamLindyWordList.json";
import loader from "../data/loader";
import JsonDataImporter from "../lib/JsonDataImporter";
import type { Params } from "react-router-dom";
import type { WordListData } from "../data/wordList";

Expand All @@ -13,7 +13,8 @@ export const wordListLoader = async ({
params: Params<string>;
}): Promise<WordListData> => {
if (params.wordListName) {
return await loader(params.wordListName);
const importer = new JsonDataImporter({ defaultData: defaultWordList });
return await importer.import(params.wordListName);
} else {
console.error(
"expected a param of 'wordListName' but didn't find one or it had a falsey value",
Expand Down

0 comments on commit 23178be

Please sign in to comment.