You would need your fetch to take place in a parent component. Then, you can render whichever component you want based on the state of fetch. If fetching is done, render the NewComponent. If still fetching, render the CurrentComponent.
import React, { useState } from "react";
import ReactDOM from "react-dom";
const CurrentComponent = () => <div>I am current</div>;
const NewComponent = () => <div>I am new</div>;
const App = () => {
const [loading, setLoading] = useState(true);
// this simulates your fetch
setTimeout(() => {
setLoading(false);
}, 2000);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
<h2>Component:</h2>
{loading ? <CurrentComponent /> : <NewComponent />}
</div>
);
};
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Or with React-Router:
Do your fetch and when your fetch completes use history.push
to go to your new route. See this post.
4
solved Dont render until data has loaded – react [closed]