I have an API with a list of names (which could change) I then want to create routes from that list but I keep getting route not found error. However when manually adding the route for a name it works. How do I add a route after the page has loaded to make it work This is my code below
function App() {
let json =[]
fetch(`${baseURL}/applications/`).then(response =>{return response.json();}).then(data =>{json=data})
console.log("json =", json)
return (
<Router>
<div className="App">
<header className="App-header">
<Routes>
<Route path="/" exact element={<ApplicationsList/>}/>
<Route path={"/1080p-Lock"} exact element={<ApplicationPage name={"1080p-Lock"}/>}/>
{json.map(item => {ReactDOM.render(<Route path={"/" item} exact element={<ApplicationPage name={item}/>}/>)})}
</Routes>
</header>
</div>
</Router>
);
}
CodePudding user response:
Issue
The React render function is a synchronous, pure function, it can't wait for asynchronous logic to complete. The json
value is reset to an empty array each render cycle.
The route mapping only needs to return the Route
components that need to be rendered, using ReactDOM
here isn't very valid.
Solution
Use component state to store the fetched data and a mounting useEffect
hook to make the fetch request.
function App() {
const [routes, setRoutes] = useState([]);
useEffect(() => {
fetch(`${baseURL}/applications/`)
.then(response => {
return response.json();
})
.then(data => {
setRoutes(data);
})
.catch(error => {
// handle any rejected Promises, etc...
});
}, []);
return (
<Router>
<div className="App">
<header className="App-header">
<Routes>
<Route path="/" element={<ApplicationsList/>}/>
<Route path={"/1080p-Lock"} element={<ApplicationPage name={"1080p-Lock"}/>}/>
{routes.map(item => (
<Route path={"/" item} element={<ApplicationPage name={item}/>}/>
))}
</Routes>
</header>
</div>
</Router>
);
}