I am relatively new to React and learning it. I am trying to get new Post using axios
. But when I hit '/getPost'
url, GetPost
component is calling continuously the backend. Is this the expected behavior?
Below is the code snippets:
// important imports
import React from 'react'
import { BrowserRouter as Router,Route, Routes }
from 'react-router-dom';
import './App.css';
import Create from './component/Create';
import Edit from './component/Edit';
import GetPost from './component/GetPost';
import Home from './component/Home';
function App () {
return (
<div className='App'>
<Router>
<Routes>
<Route path ='' element= {<Home></Home>}> </Route>
<Route path ='/edit' aelement= {<Edit/>}> </Route>
<Route path='/create' element= {<Create/>}></Route>
<Route path='/getPost' element= {<GetPost/>}></Route>
</Routes>
</Router>
</div>
)
}
export default App;
import React, { useState } from 'react';
import axios from 'axios';
const GetPost = () => {
const [person, setPerson] = useState([]);
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
console.log(res.data);
setPerson(res.data);
})
return (
person.map(p =>
<div>
{p.id}
</div>
)
)
}
export default GetPost;
CodePudding user response:
That's because of that call of axios
inside GetPost
. It executes when the components gets mounted, set the state by calling setPerson(res.data)
, it will trigger a re-render, then the axios
part gets re-executed, and that will be for ever. To avoid this, you would wanna use useEffect
hook from React.
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const GetPost = () => {
const [person, setPerson] = useState([]);
useEffect(()=>{
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
console.log(res.data);
setPerson(res.data);
})
},[])
return (
person.map(p =>
<div>
{p.id}
</div>
)
)
}
export default GetPost;
CodePudding user response:
How about fetching data in useEffect like below?
useEffect(() => {
const load = async () => {
const res = await axios.get(`https://jsonplaceholder.typicode.com/users`)
console.log(res.data);
setPerson(res.data);
}
load();
}, []);
I guess the reason GetPost component keeps being called is that you update state in the component which causes re-render the component like explained here.
CodePudding user response:
Make your API call in UseEffect to resolve this-
useEffect(()=>{
axios.get(`https://jsonplaceholder.typicode.com/users`)
.then(res => {
console.log(res.data);
setPerson(res.data);
})
},[])
Also, you make these following changes in your App.js-
<div className='App'>
<Router>
<Routes>
<Route exact path ='/' element= {<Home/>}> </Route>
<Route exact path ='/edit' element= {<Edit/>}> </Route>
<Route exact path='/create' element= {<Create/>}></Route>
<Route exact path='/getPost' element= {<GetPost/>}></Route>
</Routes>
</Router>