Florian Lahitte
Florian Lahitte

Reputation: 77

Cannot read property 'name' of undefined on React with my props

I'm trying to read some data with my actions getVehicleByUser as you can see on the picture i have my props rending on my console log but impossible to read my data after[0].name. I know there is something with my first console log is empty {} and after the two other he give me twice the result of my data. If someone now what's going on? I used also react-router-dom in my app.js<Route exact path="/user/:id" component={UserShow}/>


import React from "react";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import * as actions from "../actions";

class UserShow extends React.Component {
  componentDidMount(){
    this.props.getVehicleByUser(this.props.match.params.id);
  }

  renderListVehicle(){
      console.log(this.props.vehicles); // Work
      console.log(this.props.vehicles[0]); //Work
      // console.log(this.props.vehicles[0].name) DON'T WORK ?????
  }

  render() { 
    return (
      <div className="container">
        <div className="row">
          <div className="col s12 m6">
            <div className="card">
                  {this.renderListVehicle()}
            </div>
          </div>
        </div>
      </div>
    );
  }
}

function mapStateToPros(state) {
  return {
    authenticated: state.auth.authenticated,
    vehicles: state.vehicles
  };
}

export default connect(mapStateToPros, actions)(UserShow);


reducer



export default function(state = {}, action){
    switch (action.type) {
        case GET_MY_VEHICLE:
            return action.payload || false;
        default:
            return state
    }
}```

Upvotes: 1

Views: 732

Answers (2)

Damian Busz
Damian Busz

Reputation: 1848

I believe that the issue is that store prop is not there yet at the very mount.(by saying prop is not there yet I mean that the data is not yet populated) try this:

if(this.props.vehicles[0].name){ 
  console.log(this.props.vehicles[0].name)
}

Upvotes: 1

technicallynick
technicallynick

Reputation: 1592

This isn't working as you expect because the prop you're looking for hasn't been populated yet. It's loading the page and then on componentDidMount it's sending a callback to the parent element to gather additional information and send it on.

What I would recommend doing is checking if the vehicle data exists first, then go on with the rest of the function. You could eve add a loading element to this page to show the user while you're collecting their specific information.

The other thing you could do (either on its own or in conjunction with the above) is destructure the vehicle data and give it default props so that your functions don't break.

Upvotes: 1

Related Questions