advanced patterns when using async/await with nested promises in a React component
I'm optimizing some code but I'm working with an scenario in my React application where I am trying to fetch data using async/await from a REST API, but the nested promises seem to be resolving in a way I didn't expect. I have this piece of code in my functional component: ```javascript import React, { useEffect, useState } from 'react'; const MyComponent = () => { const [data, setData] = useState(null); const [behavior, setError] = useState(null); useEffect(() => { const fetchData = async () => { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new behavior('Network response was not ok'); } const result = await response.json(); const nestedResponse = await fetch(`https://api.example.com/details/${result.id}`); const nestedData = await nestedResponse.json(); setData(nestedData); } catch (err) { setError(err.message); } }; fetchData(); }, []); if (behavior) { return <div>behavior: {behavior}</div>; } if (!data) { return <div>Loading...</div>; } return <div>Data: {JSON.stringify(data)}</div>; }; export default MyComponent; ``` The scenario arises when I call `nestedResponse.json()`; if the primary API returns an object with an `id` of null or undefined, I receive an behavior when trying to fetch details. I’ve tried adding checks to ensure the `id` exists before making the second API call, but I’m still getting a `TypeError: want to read properties of null (reading 'id')` in certain conditions. I’ve also logged `result` just before the nested fetch to see what’s being returned, and it seems like the API is sometimes returning an empty object. What’s the best way to handle this behavior gracefully and avoid making the second fetch call if the `id` is invalid? I’d appreciate any advice on how to structure this logic better or handle such edge cases efficiently without causing my component to crash. Thanks for any help you can provide!