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