Use csv data in mobx state tree model

27 Views Asked by At

I'm very new to mobx state tree. I'm trying to use csv data from a local csv (stored in public/data/data.csv). Here's what I have in my store (file called Data.js):

import { types, flow } from "mobx-state-tree"
import { applySnapshot } from "mobx-state-tree"
import Papa from 'papaparse';

const Record = types.model({
    year: types.string,
    efficiency: types.string,
    sales: types.string
})

export const Store = types
    .model('Store',{
        data: types.array(Record)
    })
    .actions((self) => ({
        afterCreate() {
            self.load()
        },
        load: flow(function* load() {

            const url = process.env.PUBLIC_URL + 'data/data.csv'
            const response = yield window.fetch(url);
            const csvData = yield response.text();

            Papa.parse(csvData, {
                header: true,
                complete: (results) => {
                    const jsonArray = results.data;
                    console.log(jsonArray)
                    applySnapshot(self.data, jsonArray)
                },
                });
              })
        }));

In index.js I have:

import { Store } from './model/Data';
let data = Store.create()
console.log('data', toJS(data))

When I console.log from the model itself (from within the Papa.parse call) I'm able to see the data. The problem is that data is empty when I console log it from index.js. Why is that?

0

There are 0 best solutions below