0

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.

Dan Homola
  • 3,819
  • 1
  • 28
  • 43
Deepak Ranga
  • 123
  • 1
  • 1
  • 9

2 Answers2

1

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

Mark Small
  • 394
  • 1
  • 5
1

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>
  );
}
DecPK
  • 24,537
  • 6
  • 26
  • 42