Deepak Ranga
Deepak Ranga

Reputation: 123

Cannot read property in React js

In App.js

export default function App() {
    const [data, setData] = useState(null);

    useEffect(() => {
    fetch("https://api.github.com/users/deepakranga1801")
        .then((response) => response.json())
        .then(setData);
    }, []);

    return (
        <div className="App">
            <Card item={data} />
        </div>
    );
}

In Card.js

function Card(props) {
    return (
        <div><h1>{props.item.name}</h1></div>
    );
}

I'm trying to pass data fetch from API from app.js to card.js but through

TypeError Cannot read property 'name' of null.

Upvotes: 0

Views: 48

Answers (2)

DecPK
DecPK

Reputation: 25398

This behavior is because the first time when the item is passed then it would be null and it doesn't have property name on it. So either you can use optional chaining or logical AND

1) Just use the optional chaining operator in JSX

{props.item?.name}

2) Logical AND

<h1>{props.item && props.item.name}</h1>

CODE

export default function Card(props) {
  return (
    <div>
      <h1>{props.item?.name}</h1>
    </div>
  );
}

Upvotes: 1

Mark Small
Mark Small

Reputation: 414

This is happening due to the async nature of making an API request. The Card component is already rendered, before the response from the API. The first time it runs, props.item doesn't exist, therefore it throws an error. You can prevent this from happening by using props?.item?.name. You can see a decent explanation of the optional properties here

Upvotes: 1

Related Questions