Home > other >  How can I grab a CSV with Axios in a Svelte app?
How can I grab a CSV with Axios in a Svelte app?

Time:10-19

I'm new to Svelte, and am trying to figure out how to grab a CSV with Axios. It seems like it should be straightforward, but I'm not having any luck. I've tried a few different things, but nothing is getting me my data. I must be missing something? Below is my code from App.svelte file. (This is very bare bones at the moment) Would love any help. Thank you!

Update: I'm using Google Chrome version 94, and the latest version of Axios ("axios": "^0.23.0")

Also, I can get the csv if I use fetch

This is the error I'm getting:

error TypeError: Cannot convert undefined or null to object
    at Function.keys (<anonymous>)
    at mergeConfig (mergeConfig.js:92)
    at Axios.request (Axios.js:39)
    at Axios.<computed> [as get] (Axios.js:129)
    at Function.wrap [as get] (bind.js:9)
    at App.svelte:29

Code:

<script>
    import { geoAlbers, geoPath } from "d3-geo";
    import { onMount } from "svelte";
    import { feature } from "topojson-client";
    import axios from "axios";

    let nation, usstates;

    const projection = geoAlbers();
    const path = geoPath().projection(projection);

    let data;

    onMount(async function () {
        const response = await fetch(
            "https://unpkg.com/[email protected]/states-10m.json"
        );
        const json = await response.json();
        const land = feature(json, json.objects.nation);
        const states = feature(json, json.objects.states);

        nation = path(land);
        usstates = path(states);

        let data = [];
        let error = null;

        try {
            const locations = await axios.get(
                "https://docs.google.com/spreadsheets/d/e/2PACX-1vQOGtpeb5QsunVCaYXto2CGdYNOy5tDa42nZuTW198hswSmoTZUQv-LUAXMwpnSq76eHcV6aNO-Epya/pub?output=csv"
            );
            data = locations.data;
            console.log("data", data);
        } catch (e) {
            error = e;
        }
    });
</script>

<svg width="960" height="500">
    <path d={nation} class="border" />
    <path d={usstates} class="stateborder" />
</svg>

<style>
    svg {
        width: 960px;
        height: 500px;
    }
    .border {
        stroke: #444444;
        fill: #cccccc;
    }
    .stateborder {
        fill: "none";
        stroke: #fff;
        stroke-width: 0.5;
    }
</style>

CodePudding user response:

Are you getting an error? What verison of Axios are you using? I can see that your Google docs URL is sending a 307 redirect which might be causing the issue.

https://github.com/axios/axios/issues/2429 refers to what you might be experiencing.

Your code worked for me on Axios 0.21.4 and Chrome 94.

  • Related