modsell
modsell

Reputation: 25

React passing list to state from props

I have two commponents. Map and LfMap.

import React, { Component } from 'react';
import { LfMap } from '../../components/Localisation/LfMap';


export class Map extends Component {
    constructor(props) {
        super(props);

        this.state = {
            dev: [],
        };
    }
    componentDidMount() {
        fetch("URL")
        .then(resp => resp.json())
        .then(pas => this.setState({dev: pas}));
    }

    render() {

        return(
            <React.Fragment>
                <LfMap list={this.state.dev}/>
            </React.Fragment>
        );
    }
}

import React from 'react';
import { Map, CircleMarker, TileLayer, Polyline} from "react-leaflet";
import "leaflet/dist/leaflet.css";
import Control from 'react-leaflet-control';

class LfMap extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            devices: this.props.list,
        }
    }

    render() {

        return(
        <React.Fragment>
            <Map
            style={{ height: "480px", width: "100%" }}
            zoom={12}
            center={[22.22, 21.00]}
            >
                <TileLayer url="http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" />
            </Map>
        </React.Fragment>
        );
    }
}

export { LfMap };

And I'm passing a prop list to LfMap with list of my objects.

But when I'm trying to console.log(this.state.devices) it shows Undefined but it should console my list of objets which i fetched in other component. Why it's happening?

Upvotes: 1

Views: 3147

Answers (1)

Renaldo Balaj
Renaldo Balaj

Reputation: 2440

Why set state = props ? is an anti-pattern, you should keep using this.prop.list in the other component.

Do this:

console.log(this.props.list)

it will print [], and then when the results come it will print the full array.

When you need to use this array always use this.props.list.

Based in your comment here is how you give solution to that: At the parent you add a function

listUpdate(newList){
 this.setState({
    list: newList
})
}

and then you pass this function to the child

 <LfMap list={this.state.dev} listUpdate={this.listUpdate}/>

when you need to update it you need to call this.props.listUpdate. Always update the props :) that's where the reference is, this is the pattern you should follow.

Upvotes: 2

Related Questions