React setState()

338
0
11-14-2019 05:21 AM
kawishabbas
New Contributor III

Hi 

I am using esri-loader for React App. When i pass graphic to state it is not showing in my console it give blank array.

can any one guide me where i am going to mistake.

Consider line N0. 102 and 176 

import React from 'react'
import { loadModules } from 'esri-loader';
import Axios from 'axios';

export default class Database extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            capacity: ['96F'],
            comment: ['kawish'],
            placement: ['buried'],
            pop: ['2100360'],
            geom:[]

        }
        this.button = React.createRef()
        this.line_button = React.createRef()
    }

    componentDidMount() {

         let view = this.props.view
        let graphic

        loadModules(["esri/widgets/Sketch","esri/tasks/support/Query", "esri/tasks/QueryTask", 'esri/widgets/Expand',
            "esri/Graphic", "esri/views/draw/Draw", "esri/geometry/geometryEngine", "esri/layers/GraphicsLayer"
        ])
            .then(([Sketch, Query, QueryTask, Expand, Graphic, Draw, geometryEngine, GraphicsLayer]) => {


                view.ui.add(this.button.current, 'top-left')

                // add the button for the draw tool
                view.ui.add(this.line_button.current, "top-left");

                const draw = new Draw({
                    view: view
                });

                // draw polyline button
                this.buttonClick = (e) =>{
                    // view.graphics.removeAll();

                    // creates and returns an instance of PolyLineDrawAction
                    const action = draw.create("polyline");

                    // focus the view to activate keyboard shortcuts for sketching
                    view.focus();

                    // listen polylineDrawAction events to give immediate visual feedback
                    // to users as the line is being drawn on the view.
                    action.on(
                        [
                            "vertex-add",
                            "vertex-remove",
                            "cursor-update",
                            "redo",
                            "undo",
                            "draw-complete"
                        ],
                        updateVertices
                    );
                }
            

                // Checks if the last vertex is making the line intersect itself.
                function updateVertices(event) {
                
                    // create a polyline from returned vertices
                    if (event.vertices.length > 1) {
                        const result = createGraphic(event);

                        // if the last vertex is making the line intersects itself,
                        // prevent the events from firing
                        if (result.selfIntersects) {
                            event.preventDefault();
                        }
                    }
                }

                // create a new graphic presenting the polyline that is being drawn on the view
                const createGraphic =  (event) =>{
                    const vertices = event.vertices;
                    view.graphics.removeAll();

                    // a graphic representing the polyline that is being drawn
                     graphic = new Graphic({
                        geometry: {
                            type: "polyline",
                            paths: vertices,
                            spatialReference: view.spatialReference
                        },
                        symbol: {
                            type: "simple-line", // autocasts as new SimpleFillSymbol
                            color: [4, 90, 141],
                            width: 4,
                            cap: "round",
                            join: "round"
                        }
                    });
                    this.setState({
                        geom:graphic.geometry
                    })
                
                    // check if the polyline intersects itself.
                    const intersectingSegment = getIntersectingSegment(graphic.geometry);

                    // Add a new graphic for the intersecting segment.
                    if (intersectingSegment) {
                        view.graphics.addMany([graphic, intersectingSegment]);
                    }
                    // Just add the graphic representing the polyline if no intersection
                    else {
                        view.graphics.add(graphic);
                    }

                    // return intersectingSegment
                    return {
                        selfIntersects: intersectingSegment
                    };
                }

                // function that checks if the line intersects itself
                function isSelfIntersecting(polyline) {
                    if (polyline.paths[0].length < 3) {
                        return false;
                    }
                    const line = polyline.clone();

                    //get the last segment from the polyline that is being drawn
                    const lastSegment = getLastSegment(polyline);
                    line.removePoint(0, line.paths[0].length - 1);

                    // returns true if the line intersects itself, false otherwise
                    return geometryEngine.crosses(lastSegment, line);
                }

                // Checks if the line intersects itself. If yes, change the last
                // segment's symbol giving a visual feedback to the user.
                function getIntersectingSegment(polyline) {
                    if (isSelfIntersecting(polyline)) {
                        return new Graphic({
                            geometry: getLastSegment(polyline),
                            symbol: {
                                type: "simple-line", // autocasts as new SimpleLineSymbol
                                style: "short-dot",
                                width: 3.5,
                                color: "yellow"
                            }
                        });
                    }
                    return null;
                }

                // Get the last segment of the polyline that is being drawn
                function getLastSegment(polyline) {
                    const line = polyline.clone();
                    const lastXYPoint = line.removePoint(0, line.paths[0].length - 1);
                    const existingLineFinalPoint = line.getPoint(
                        0,
                        line.paths[0].length - 1
                    );

                    return {
                        type: "polyline",
                        spatialReference: view.spatialReference,
                        hasZ: false,
                        paths: [
                            [
                                [existingLineFinalPoint.x, existingLineFinalPoint.y],
                                [lastXYPoint.x, lastXYPoint.y]
                            ]
                        ]
                    };
                }
               console.log(this.state.geom)
            });
    }

    save = async (e) =>{
        //console.log(e)
        const params = new URLSearchParams();
        params.append('capacity', 'haseeb');
        params.append('comment', this.state.comment);
        params.append('placement', this.state.placement);
        params.append('pop', this.state.pop);
       // params.append('geom', this.state.geom);
    
        await Axios.post("http://localhost:8080/post", params)
            .then(response => console.log(response.data))
            .catch((err) => console.log(err));
    }
    render() {
        return (
            <div>
                <div
                    ref={this.line_button}
                    class="esri-widget esri-widget--button esri-interactive"
                    title="Draw polyline"
                    onClick={(e) => this.buttonClick(e)}
                >
                    <span class="esri-icon-polyline"></span>
                </div>
                <form>
                    <label>Capacity</label>
                    <input type="text" />

                    <label>Comment</label>
                    <input type="text" />

                    <label>Placement</label>
                    <input type="text" />

                    <label>POP</label>
                    <input type="text" />

                    <label>Geometry</label>
                    <input type="text" /><br />

                    <button ref={this.button} onClick={this.save}>Save</button>

                </form>

            </div>


        )

    }

}

0 Kudos
0 Replies