import React from "react";
import avatar from "../../assets/img/avatar.png";
import styles from "./users.module.css";
import axios from "axios";
class Users extends React.Component{
componentDidMount() {
axios.get('https://social-network.samuraijs.com/api/1.0/users')
.then(response => this.props.setUsers(response.data.items))
}
render() {
return (
<div className={styles.users}>
{
this.props.users.map(user =>
<div className={styles.inner}>
<div className={styles.user}>
<img src={user.photos.small ? user.photos.small : avatar} alt="avatar" width={60} height={60}/>
{
user.followed ?
<button className={styles.following} onClick={() => this.props.unfollow(user.id)}>Отписаться</button> :
<button className={styles.following} onClick={() => this.props.follow(user.id)}>Подписаться</button>
}
</div>
<div className={styles.info}>
<div className={styles.about}>
<h3 className={styles.name}>
{user.name}
</h3>
<p className={styles.status}>
{user.status}
</p>
</div>
<div className={styles.location}>
<p className={styles.city}>
Vladivostok
</p>
<p className={styles.country}>
Russia
</p>
</div>
</div>
</div>
)
}
</div>
)
}
}
export default Users;
const FOLLOW = 'FOLLOW';
const UNFOLLOW = 'UNFOLLOW';
const SET_USERS = 'SET_USERS';
const initialState = {
users: []
}
const usersReducer = (state = initialState, action) => {
switch (action.type){
case FOLLOW: {
return {
...state,
users: state.users.map(user => {
if (user.id === action.userId){
return {...user, followed: true};
}
return user;
})
}
}
case UNFOLLOW: {
return {
...state,
users: state.users.map(user => {
if (user.id === action.userId){
return {...user, followed: false};
}
return user;
})
}
}
case SET_USERS: {
return {
...state,
users: [...state.users, ...action.users]
}
}
default:
return state;
}
}
export const followCreator = (userId) => ({type: FOLLOW, userId});
export const unfollowCreator = (userId) => ({type: UNFOLLOW, userId});
export const setUsersCreator = (users) => ({type: SET_USERS, users});
export default usersReducer;
import { connect } from "react-redux";
import { followCreator, setUsersCreator, unfollowCreator } from "../../redux/usersReducer";
import Users from "./Users";
const mapStateToProps = (state) => {
return {
users: state.USERS_PAGE.users
}
}
const mapDispatchToProps = (dispatch) => {
return {
follow: (userId) => {
dispatch(followCreator(userId));
},
unfollow: (userId) => {
dispatch(unfollowCreator(userId));
},
setUsers: (users) => {
dispatch(setUsersCreator(users));
}
}
}
const UsersContainer = connect(mapStateToProps, mapDispatchToProps)(Users);
export default UsersContainer;
<React.StrictMode>
метод жизненного цикла ComponentDidMount
отрабатывает дважды. Документация.