I have this App component which I want to get some data from my API on the back:
const App = () => { const [restaurants, setRestaurants] = useState(""); useEffect(() => { const fetchData = async () => { try { const response = await fetch( "http://localhost:3001/api/v1/restaurants" ); const data = await response.json(); console.log(data); setRestaurants(data); } catch (err) { console.log("Cant fetch"); } }; fetchData(); }, []); return ( // <RestaurantContextProvider> <div className="container"> <Router> <Routes> <Route exact path="/" element={<Home restaurants={restaurants} />} /> <Route exact path="/restaurants/:id/update" element={<UpdatePage />} /> <Route exact path="/restaurants/:id" element={<RestaurantDetailPage />} /> </Routes> </Router> </div> // </RestaurantContextProvider> ); }; export default App; If I change the element for a component in the Route element, it fetches but does not render. What is wrong? I did not find the answer on the V6 documentation of the Router.
Edited:
If i add the fetch inside this component, it fetch the data OK.
const RestaurantsList = (restaurants) => { return ( <div className="list-group"> <table className="table table-hover table-dark"> <tbody> {restaurants && restaurants.map((res) => ( <tr key={res.id}> <td>{res.name}</td> <td>{res.location}</td> <td>{"$".repeat(res.price_range)}</td> <td>Reviews</td> <td> <button className="btn btn-warning">Update</button> </td> <td> <button className="btn btn-danger">Delete</button> </td> </tr> ))} </tbody> </table> </div> ); }; export default RestaurantsList; Here it is the index.js:
import React from "react"; import ReactDOM from "react-dom"; import App from "./App"; ReactDOM.render(<App />, document.getElementById("root"));
<Route render={(routerProps => <Home restaurants={restaurants} {...routerProps} />