CSV Store
Summary
This module creates a store for loading and accessing data from static CSV files. It is designed so data can be loaded from a series of CSV files as needed, instead of loading a large file all at once. Built using:
- zustand (provides base store)
- d3-dsv (for parsing)
- axios (for file requests)
Usage
npm i static-csv-store
; // create the storeconst useStore = ;
See zustand documentation on how to use the store. The state of the store will have the following properties:
Properties
data
: an object containing all of the loaded data. each data entry is stored as an array of values with the primary key (defaultid
) as the key.loading
: an array of the files currently loadingloaded
: an array of files that have been loaded into the storeerrors
: an array of errors that have occured when loading files
Methods
loadFile({ file, key, parser })
: a function that loads a csv file into the data storefile
: the filename to load from the endpoint (e.g./texas/schools.csv
)key
: the column name to use as the primary keyparser
: a function to parse each row (default:d3.autoType
)
getData({ filters, columns })
: a function for retrieving data from the storefilters
: an array of filters to filter data in the storecolumns
: an array of columns to keep in the returned data
Example
Take a look at the demo (/demo/src
) for a closer look at how to use the store.
1. Create a store for CSV data
File: store.js
; // create the storeconst useStore _api = ; // you can export the `useStore` hook as is// but it is nice to provide some shorthand// hooks for common use cases // shorthand to provide loaderconst useLoader = ; // shorthand to provide dataconst useData = { const data = ; const columnMap = ; return ;}; // provide api for use outside of Reactconst api = _api; // provide store;
2a. Use the store in a React component
; // component re-renders any time data changes { // get loader for the store const loadFile = ; // get the data from the store const allSchools = ; // load schools for a county whenever county changes ; return <ul> allSchools </ul> ;}
2b. Use the store without React
; // Get the file loaderconst loadFile = apiloadFile; // subscribe to data in the stateconst unsub = api; // Load a file; // Unsubscribe listeners with unsub()// Destroying the store (removing all listeners) with api.destroy()