0

fetching data from mysql but unable to store that data in a state. I'm building user live location. users data is located in mysql and im fetching that data and trying to show data in google map.

import { React, useState, useEffect } from "react";
    import "./App.css";
    import axios from "axios";
    import {
      GoogleMap,
      withScriptjs,
      withGoogleMap,
      Marker,
      InfoWindow,
    } from "react-google-maps";
    
    function Map() {
      const [selectedPark, setSelectedPark] = useState([]);
      var data = "";
      var config = {
        method: "get",
        url: "http://localhost:3002/user",
        headers: {},
        data: data,
      };
      useEffect(() => {
        axios(config)
          .then(function (response) {
            console.log(JSON.stringify(response.data));
            setSelectedPark(response.data);
            console.log(selectedPark);
          })
          .catch(function (error) {
            console.log(error);
          });
      }, []);
      return (
        <GoogleMap
          defaultZoom={10}
          defaultCenter={{ lat: 24.860966, lng: 66.990501 }}
        >
          {selectedPark.map((park) => (
            <Marker
              key={park.user_Id}
              position={{
                lat: park.latitude,
                lng: park.longitude,
              }}
              onClick={() => {
                setSelectedPark(park);
              }}
              onCloseClick={() => {
                setSelectedPark(null);
              }}
              icon={{
                url: "https://raw.githubusercontent.com/leighhalliday/google-maps-react-demo/2bcd4ca7184ea9ed9edbc25021c2e721a74c027f/public/skateboarding.svg",
                scaledSize: new window.google.maps.Size(25, 25),
              }}
            />
          ))}
          {selectedPark && (
            <InfoWindow
              position={{
                lat: selectedPark.latitude,
                lng: selectedPark.longitude,
              }}
            >
              <div>
                <h2>{selectedPark.area_name}</h2>
                <p>{selectedPark.area_description}</p>
              </div>
            </InfoWindow>
          )}
        </GoogleMap>
      );
    }
    const WrappedApp = withScriptjs(withGoogleMap(Map));
    function App() {
      return (
        <div style={{ width: "100vw", height: "100vw" }}>
          <WrappedApp
            googleMapURL={`https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=geometry,drawing,places&key=AIzaSyDmVpJ44AZEUIs-ml0R1Q0URcmr-Q-DMC4`}
            loadingElement={<div style={{ height: "100%" }} />}
            containerElement={<div style={{ height: "100%" }} />}
            mapElement={<div style={{ height: "100%" }} />}
          />
        </div>
      );
    }
    
    export default App;

server is working perfectly, i can see the data from console, it works fine but the only problem is that im unable to store that data in a state

enter image description here

nbk
  • 45,398
  • 8
  • 30
  • 47

2 Answers2

0

React batches setState , so you can't see the change immediately. Do this

Add one more useEffect

useEffect(()=>{
   console.log(selectedPark)
},[selectedPark])

-1
useEffect(() => {
   const fetchData = async () => {
        axios(config)
        .then(response => response.json())
        .then(response => setSelectedPark(response.data))
        .catch(function (error) {
          console.log(error);
        });
   }

   fetchData();
}, []);

Try this example of request in useEffect, diff with your code that in my example I return data from promise using promise chain (1st then call json method, 2nd then return clear data and save in state)

For more comfortable debugging you can console.log in a place when you saving your data in a state

CuteShaun
  • 139
  • 7