New Object created with JS returns empty values

Viewed 43

I want my function calculateDistance to return a new array based on the array in state.

so once a user presses a button, handle method is activated:

 handleSearch(result){
        this.setState({
            teams: this.calculateDistance(result),
        })        
}

calculateDistance(result){
        let map = L.map('route-map').setView([52.237049, 21.017532], 11);
        const newTeams = []
        this.state.teams.forEach((team) => {
            const newTeam = {}
            let routeControl = L.Routing.control({
                waypoints: [
                    L.latLng(team.lat, team.long),
                    L.latLng(result.y, result.x)
                ],
                show: true,
              }).addTo(map)
            routeControl.on('routesfound', function(e) {
                let routes = e.routes;
                let dist = routes[0].summary.totalDistance;
                Object.defineProperty(newTeam, 'distance', {
                    value: dist,
                    writable: false
                })
                Object.defineProperty(newTeam, 'id', {
                    value: team.id,
                    writable: false
                })
            })
            newTeams.push(newTeam)
        })
        return newTeams

this.state.teams is a array retrieved from axios GET method. Firstly I tried to add a new value, for each team. It worked for the object but not with stringify - and that resulted in no change. Then I figured I will create a new Object, and that is the code mentioned in this question. I tried using async. And it did indeed return a promise with the result (I checked in using console.log(promise) but state wasn't updated anyway (after using .then(), there wasn't any value).

1 Answers

The object you create only appears to be empty. By default defineProperty creates a property that is not enumerable.

You can to change your code to make them enumerable:

                Object.defineProperty(newTeam, 'distance', {
                    value: dist,
                    writable: false,
                    enumerable: true
                })
                Object.defineProperty(newTeam, 'id', {
                    value: team.id,
                    writable: false,
                    enumberable: true
                })
Related