Reputation: 115
I actually face a small problem in React when calling the API, since ComponentWillMount
is deprecated.
I did this:
class MyClass extends Component {
constructor() {
super();
this.state = {
questionsAnswers: [[{ answers: [{ text: '', id: 0 }], title: '', id: 0 }]],
},
};
}
componentDidMount() {
this.getQuestions();
}
getQuestions = async () => {
let questionsAnswers = await Subscription.getQuestionsAndAnswers();
questionsAnswers = questionsAnswers.data;
this.setState({ questionsAnswers });
};
So the page is rendered a first time without questionsAsnwers
, when I get the questionAnswers
the page is re-rendered
Is there a better solution to avoid a re-render?
Upvotes: 5
Views: 12248
Reputation: 70184
Using a class with React.Component
it is componentDidMount
:
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
items: []
};
}
componentDidMount() {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
this.setState({
isLoaded: true,
items: result.items
});
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
this.setState({
isLoaded: true,
error
});
}
)
}
render() {
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}
}
If you use a function component with Hooks you should do it like this:
function MyComponent() {
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [items, setItems] = useState([]);
// Note: the empty deps array [] means
// this useEffect will run once
// similar to componentDidMount()
useEffect(() => {
fetch("https://api.example.com/items")
.then(res => res.json())
.then(
(result) => {
setIsLoaded(true);
setItems(result);
},
// Note: it's important to handle errors here
// instead of a catch() block so that we don't swallow
// exceptions from actual bugs in components.
(error) => {
setIsLoaded(true);
setError(error);
}
)
}, [])
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
return (
<ul>
{items.map(item => (
<li key={item.id}>
{item.name} {item.price}
</li>
))}
</ul>
);
}
}
Example response:
{
"items": [
{ "id": 1, "name": "Apples", "price": "$2" },
{ "id": 2, "name": "Peaches", "price": "$5" }
]
}
Source:
https://reactjs.org/docs/faq-ajax.html
Upvotes: 2
Reputation: 325
The best way to handle API call is in the componentDidMount
method react lifeCycle according to react documentation. At this moment all you can do is to add a spinner to make your component more user-friendly.
Hopefully, in the next React releases. React will introduce a new way to solve this kind of problem using the suspense
approach https://medium.com/@baphemot/understanding-react-suspense-1c73b4b0b1e6
Upvotes: 3
Reputation: 1773
I think, it's okay to show spinner in that situation. And you should also check that ajax did not fail.
Upvotes: 0