Home  • Programming • React

Fetch Data Before Render in the Parent

If you absolutely need to run some code before a component renders, then the solution is to avoid rendering that component at all, until you’re ready. That means conditionally rendering it in the parent, which would look something like this. More detail in the comments:
function Child({ items }) {
  // Problem:
  // This will error if `items` is null/undefined
  return (
    <>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </>
  );
}

function Parent() {
  // Uninitialized state will cause Child to error out
  const [items, setItems] = useState();

  // Data does't start loading
  // until *after* Parent is mounted
  useEffect(() => {
    fetch('/data')
      .then(res => res.json())
      .then(data => setItems(data));
  }, []);

  // Solution:
  // don't render Child until `items` is ready!
  return (
    <div>
      {items && <Child items={items}/>}
    </div>
  );
}

Comments 0


Copyright © 2024. Powered by Intellect Software Ltd