Reputation: 1786
I have a React functional component Users, which takes a parameter, a URL, which was received by an API call.I want to use this parameter to fetch some data, however when reloading on that page it renders nothing because the parameter is undefined. It also gives an error. It works however when I switch between pages, because then the URL is loaded.
My code:
App.js
function App() {
const [structure, setStructure] = useState({});
useEffect(() => {
// API CALL
fetchStructure().then((result) => setStructure(result));
}, []);
// removed some parts of the layout
return (
<div className="bodydiv">
<Switch>
<Route path="/users" ><Users url={structure.users} /></Route>
<Route path="/cars"><Cars url={structure.cars} /></Route>
<Route path="/offers" ><Offers url={structure.offers} /></Route>
</Switch>
</div>
);
}
export default App;
Users.js
import React, { useState, useEffect } from 'react';
import { Typography } from '@material-ui/core';
import {fetchUsers} from '../Api';
function Users(props) {
const [users, setUsers] = useState([]);
useEffect(() => {
//API CALL
fetchUsers(props.url).then((result) => setUsers(result));
}, []);
return (
<div>
{(users || []).map((user) => (
<Typography variant="h3" gutterBottom >{user.name}</Typography>
))}
</div>
);
}
export default Users;
How can the function "wait" for the props.url to be loaded?
Upvotes: 2
Views: 1151
Reputation: 1194
You need to add dependecies to your useEffect
like this
function Users(props) {
const [users, setUsers] = useState([]);
useEffect(() => {
//API CALL
fetchUsers(props.url).then((result) => setUsers(result));
}, [props.url]);
.....
So when props.url changes the useEffect
will be called again, in your case it is called only once. And it is when you don't have a link yet. You can read about useEffect more here
Upvotes: 1