Estoy intentando que cuando un usuario siga a otro, el botón de seguir cambie a "unfollow" y viceversa.
Soy bastante nueva en programación, hasta el momento he conseguido que la funcionalidad se ejecute, pero en el momento de hacer click el botón no cambia de manera inmediata, si no que tengo que refrescar la página para que cambie.
He estado buscando en internet pero no encuentro la solución a mi problema. Alguien sabe cómo puedo solucionar esto?
Este es mi código:
Followers:
import React from "react";
import axios from "axios";
import withUser from "./Withuser"
import { Button, Card, CardBody, CardTitle } from 'reactstrap'
class Followers extends React.Component {
constructor(props) {
super(props)
this.state = {
users: [],
//follower: [],
following: [],
followingUsers: []
}
}
componentDidMount = () => {
this.getUsers()
this.getFollowing()
}
getUsers = async () => {
try {
const response = await axios(`http://localhost:7001/api/users`)
this.setState({ users: response.data})
console.log(response.data)
} catch {
this.setState({ error: true })
}
}
getFollowing = async () => {
const userId = this.props.user[0].id
try {
const response = await axios(`http://localhost:7001/api/users/${userId}/following`)
const tempFollowing = response.data.map((follow, index) => {
return follow.followedId
})
this.setState({
following: response.data,
followingUsers: tempFollowing
})
console.log(response.data)
} catch (error) {
this.setState({ error: true})
}
}
followUser = async (e) => {
e.preventDefault();
const userId = this.props.user[0].id
const followedId = e.target.value
try {
const response = await axios.post(`http://localhost:7001/api/users/${userId}/follow/${followedId}`, {
userId,
followedId,
followed: 1,
createdAt: new Date().toISOString().slice(0, 10),
updatedAt: new Date().toISOString().slice(0, 10)
})
console.log(response.data)
this.setState(state => ({
loggedIn: !state.loggedIn,
followed: true,
}))
} catch(error) {
console.log(error)
}
}
unfollowUser = async (e) => {
e.preventDefault();
const userId = this.props.user[0].id;
const followedId = e.target.value;
try {
const response = await axios.delete(
`http://localhost:7001/api/users/${userId}/unfollow/${followedId}`
);
console.log(response);
let array = [...this.state.following];
let index = array.indexOf(followedId);
if (index !== -1) {
array.splice(index, 1);
const tempFollowing = array.map((follow, index) => {
return follow.followedId;
});
this.setState({
following: array,
followingUsers: tempFollowing,
});
}
} catch (error) {
this.setState({ error: true });
}
};
render() {
const { users, following, followingUsers } = this.state
const userId = this.props.user[0].id
//console.log(followingUsers)
return (
<div>
<h2>Users in Unax</h2>
<ul>
{users.map((user, index) => {
if(user.id !== userId) {
return (
<Card className="users" key= {index}>
<CardBody>
<CardTitle>{user.user_name}</CardTitle>
{followingUsers.includes(user.id) ? (
<Button id="btn-1" value={user.id} onClick={this.unfollowUser}>Unfollow</Button>
) : (
<Button id="btn" value={user.id} onClick={this.followUser}>follow</Button>
)}
</CardBody>
</Card>
)}
})}
</ul>
<div>
<h2>Following</h2>
<ul>
{following.map((follow, index) => {
return (
<Card key= {index}>
<CardBody>
<CardTitle>{follow.followedId}</CardTitle>
</CardBody>
</Card>)
})}
</ul>
</div>
</div>
)
}
}
export default withUser(Followers)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
WithUser:
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const fetchProfile = async () => {
const token = localStorage.getItem('token');
if (!token) {
throw new Error('Missing Token');
}
const response = await axios('http://localhost:7001/api/profile', {
headers: {
'x-access-token': token,
},
});
const profile = response.data;
return profile;
};
const fetchUsers = async (userId) => {
const response = await axios(`http://localhost:7001/api/users/${userId}`);
const users = response.data;
return users;
};
const withUser = (Component, options = { renderNull: true }) => (props) => {
const [userData, setUserData] = useState();
useEffect(() => {
async function loadUser() {
try {
const profile = await fetchProfile();
const users = await fetchUsers(profile.id);
setUserData(users);
} catch (error) {
console.error(error);
}
}
loadUser();
}, []);
if (userData === undefined && options.renderNull === true) {
return null;
}
return <Component {...props} user={userData} />;
};
export default withUser;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
Sería de gran ayuda, ya que ando un poco perdida y no he encontrado solución online.
Gracias ;)
console.log(followingUsers)
en tu funciónrender()
obtienes la lista correcta de usuarios?