In class based Component:
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
this.setState({
posts: res.data.slice(0, 10)
});
console.log(posts);
})
}
I tried this:
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
setPosts(res.data.slice(0, 10));
console.log(posts);
})
});
It creates an infinite loop. If I pass a []/{} as the second argument[1][2], then it blocks further call. But it also prevents the array from updating.
[1] Infinite loop in useEffect
[2] How to call loading function with React useEffect only once
Put the fetchData function above in the useEffect hook and call it, like so: useEffect(() => { const url = "https://api.adviceslip.com/advice"; const fetchData = async () => { try { const response = await fetch(url); const json = await response. json(); console. log(json); } catch (error) { console.
create({ baseURL: "https://example.com" }) export default instance; As we need React component to use the hooks, let's write a component here. Adding an interceptor in a component is a side effect, so we get help from useEffect hook. Add the interceptors to the Axios instance in the useEffect .
Giving an empty array as second argument to useEffect
to indicate that you only want the effect to run once after the initial render is the way to go. The reason why console.log(posts);
is showing you an empty array is because the posts
variable is still referring to the initial array, and setPosts
is also asynchronous, but it will still work as you want if used in the rendering.
Example
const { useState, useEffect } = React;
function App() {
const [posts, setPosts] = useState([]);
useEffect(() => {
setTimeout(() => {
setPosts([{ id: 0, content: "foo" }, { id: 1, content: "bar" }]);
console.log(posts);
}, 1000);
}, []);
return (
<div>{posts.map(post => <div key={post.id}>{post.content}</div>)}</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/[email protected]/umd/react.production.min.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js"></script>
<div id="root"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With