E
E
Egor Telnov2020-02-07 10:18:34
JavaScript
Egor Telnov, 2020-02-07 10:18:34

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>
    );
};

Doesn't work properly. If you go to another "page" and then return to this one, the component makes a request again and draws the same result to the end. How to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Pavel Didenko, 2020-02-07
@telnov_magic

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 question

Ask a Question

731 491 924 answers to any question