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.

2 Answers 2

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>
  );
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you.. it worked! & understood where I was wrong
Would you mind accepting my answer if it solved your issue?
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.