Prop is marked as required in component, but its value is `undefined`

Charles Duporge picture Charles Duporge · Nov 8, 2017 · Viewed 59.5k times · Source

single.js :

import React, { Component } from 'react';
import Details from '../components/details'
import { ProgressBar } from 'react-materialize';
import { Route, Link } from 'react-router-dom';

const Test = () => (
  <div> RENDER PAGE 1</div>
)

class SinglePage extends Component {

  constructor(props) {
    super(props);

    this.state = {
      data: null,
    }
  }

    componentDidMount() {
        fetch('http://localhost:1337/1')
      .then((res) => res.json())
      .then((json) => {
        this.setState({
          data: json,
        });
      });
    }

  render() {

    const { data } = this.state;

    return (

      <div>

        <h2> SinglePage </h2>

        {!data ? (
          <ProgressBar />
        ) : (
          <div>
            <Details data={data} />
          </div>
        )}
      </div>
    );
  }

}

export default SinglePage;

details.js :

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class Details extends Component {

  static propTypes = {
    item: PropTypes.shape({
      date: PropTypes.string.isRequired,
    }).isRequired,
  }


    render() {
        const { item } = this.props;

        return (
            <div>
                <p> {item.date} </p>
            </div>
        )
    }
}

export default Details;

In console, I am getting an error : Warning: Failed prop type: The prop item is marked as required in Details, but its value is undefined.

From this I though my json was not catched but I have an other component which fetch on http://localhost:1337/ , get datas and display them correctly, and going to http://localhost:1337/1 send me a json response so I'm quite confused here.

Additional screenshot : enter image description here

Answer

Shawn Janas picture Shawn Janas · Nov 8, 2017

SinglePage is passing date props with name data as oppose to item that is defined in Details

<Details item={date} />

Also adding init value for date

constructor(props) {
    super(props);
    this.state = {
        date: { date: null },
    }
}