Search code examples
javascriptreactjsleafletreact-leafletpapaparse

React Leaflet first object is undefined in a useState case for drawing map markers


I am trying to loop through an object that has been parsed from a CSV file of Locations, and Lat/Lng pairs. But when I loop through this object, the first loop returns my object with all the values as undefined. My code is as follows:

import React, { Component, useState, useEffect } from 'react';
import { LatLng } from 'leaflet';
import { Map, TileLayer, CircleMarker, Popup, Marker } from 'react-leaflet';
import CovidCasesClean from './CovidCasesClean.csv';
import Papa from 'papaparse';

export default function PlaceMarker() {
    const latlng = [null];
    const [rows, setRows] = React.useState([])
    const [data, setData] = React.useState({});

    React.useEffect(() => {
      async function getData() {
        const response = await fetch('/data/CovidCasesClean.csv')
        const reader = response.body.getReader()
        const result = await reader.read() // raw array
        const decoder = new TextDecoder('utf-8')
        const csv = decoder.decode(result.value) // the csv text
        console.log(csv)
        const results = Papa.parse(csv, { header: true, skipEmptyLines: true}) // object with { data, errors, meta }
        console.log(results)
        const rows = results.data
        console.log(rows)
        // array of objects
        setRows(rows)
        rows.map((item, i) => {
          const rowObj = {item}
          //console.log(rowObj)
          console.log(i)
          setData({
            ...data, key: i, ...data, location: rowObj.item.Location, ...data, latitude: parseFloat(rowObj.item.Latitude), ...data, longitude: parseFloat(rowObj.item.Longitude), ...data, cases: parseFloat(rowObj.item.TotalCases)
          })
        })
      }
      getData()
    }, []) // [] means just do this once, after initial render
    return (
      <div>{console.log(data.key, data.location, data.latitude, data.longitude, data.cases)}</div> 
    )
  }

When the console line: <div>{console.log(data.key, data.location, data.latitude, data.longitude, data.cases)}</div> is ran, the first result returns:

undefined undefined undefined undefined undefined

whereas the second run through returns the correct object like so:

0 Barking and Dagenham 53.546299 -1.46786 18

This causes my creating a marker object to fail as the first object is not a latlng pair, I have been trying to create markers like so:

<Marker position={(data.longitude, data.latitude)}>
  <Popup>
    <span>
      A pretty CSS3 popup.
      <br />
      Easily customizable.
    </span>
  </Popup>
</Marker>;

This is where the error occurs ^ Any ideas where I am going wrong, this is my first react project any help appreciated!

CSV file format:

Location,TotalCases,Latitude,Longitude
Barking and Dagenham,18,53.546299,-1.46786
Barnet,28,51.605499,-0.207715

Solution

  • What you are trying can be achieved in a much simpler way.

    Parse the csv data inside an useEffectHook. You do not need any of these:

    const response = await fetch('/data/CovidCasesClean.csv') const reader = response.body.getReader() const result = await reader.read() // raw array const decoder = new TextDecoder('utf-8') const csv = decoder.decode(result.value) // the csv text console.log(csv)

     const [data, setData] = useState([]);
    
      useEffect(() => {
        Papa.parse(csv, {
            download: true, // use this option to interpret the input string as a URL from which to download the input file.
            header: true,
            skipEmptyLines: true,
            complete: results => setData(results.data)
        });
      }, []);
    

    and once you store the csv parsed markers data loop over them to visualize the markers:

    {data &&
        data.map(({ Location, Latitude, Longitude, TotalCases }, i) => (
          <Marker
            key={`markers-${i}`}
            position={[Latitude, Longitude]}
            icon={icon}
          >
            <Popup>
              <span>
                <b>Location</b>: {Location}
                <br />
                <b>TotalCases</b>: {TotalCases}
              </span>
            </Popup>
          </Marker>
        ))}
    

    Demo