Answer the question
In order to leave comments, you need to log in
How to make a request to the server using react hooks?
When rendering a component, I need to make a request to the server and draw the resulting data. You need to do this only during the initial rendering of the component. Wrote this code:
const Users = props => {
useEffect(() => {
axios
.get('https://social-network.samuraijs.com/api/1.0/users')
.then(response => {
props.setUsers(response.data.items)
})
}, []);
return (
<div className="">
{props.users.map(user => (
<div className="" key={user.id}>
<div className="">
<img src={user.img} alt="" />
{user.followed === true ? (
<button onClick={() => props.unfollow(user.id)}>
Отписаться
</button>
) : (
<button onClick={() => props.follow(user.id)}>
Подписаться
</button>
)}
</div>
<div className="">
<div className="">
<p>{user.name + " " + user.lastname}</p>
<p>{user.status}</p>
</div>
<div className="">
<p>{user.location.country}</p>
<p>{user.location.city}</p>
</div>
</div>
</div>
))}
</div>
);
};
Answer the question
In order to leave comments, you need to log in
If you go to another page, then the component is unmounted and when you enter the page it is mounted again, at this moment you send the request again. So everything works correctly. In order not to pull the request again, you need to store the previous result of the request in the global store and check if there is data - do not pull a new request
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question