Reputation: 15
I'm working on a React app with Redux (thunk).
I have a list of users in this table :
function DataUsers() {
const users = useSelector((state: any) => state.userReducer.infos);
const now = 60;
const history = useHistory();
return (
<div className="tableCardDataUsers">
<Table className="table" bordered hover responsive>
<thead>
<tr className="tableHeader">
<th>ID</th>
<th>Nom</th>
<th>Email</th>
<th>Date de création</th>
<th>Numéro de téléphone</th>
<th>Pourcentage</th>
<th>Catégories</th>
</tr>
</thead>
<tbody>
{users.slice(0, 20).map((item: any, index: number) => (
<tr
className="redirectUser"
onClick={() => history.push("/Utilisateurs")}
key={index}
>
<td>{item.id}</td>
<td>
{item.nom} {item.prenom}
<br></br>Tcheker
</td>
<td>{item.email}</td>
<td>18/10/1998</td>
<td>{item.tel}</td>
<td>
<ProgressBar now={now} label={`${now}%`} />
</td>
<td className="tableCategorie">
<Button
name="VDR"
name2=""
class="catButtonMini"
color="orange"
onclick={() => {}}
type="button"
data=""
image=""
/>
</td>
</tr>
))}
</tbody>
</Table>
</div>
);
}
I want to get the id of the user onClick and then dispatch an action to display the user infos on a new page.
I made this action to get the user infos :
export const getUserById = (id_user: number | string) => {
return async (dispatch: any) => {
dispatch(isLoading(true));
try {
const res = await axios.get(`users/getUserById/${id_user}`);
dispatch(isLoading(false));
dispatch({ type: GET_USER_BY_ID, payload: res.data });
} catch (err) {
console.log(err);
dispatch(isLoading(false));
}
};
I'm usually using useSelector in my component to get datas like so :
const user = useSelector((state: any) => state.userReducer.getUserById);
I'm wondering what is the best way to pass the id_user in my action when clicking on a user cell to display it on a new user page.
Thank you
Upvotes: 0
Views: 881
Reputation: 5497
The issue is you are trying to use useSelector
to dispatch an action . useSelector
is to read the data from the store .
To dispatch an action in redux
you need to use useDispatch
. So you can change your code in your component as
import { useDispatch } from "react-redux";
import {getUserById } from 'your path
Now inside your component you can do
const UserInfo = () => {
const dispatch = useDispatch();
// get the user id , either from the store or from url params
useEffect(() => {
dispatch(getUserById(passyourId));
}, [dispatch]);
return <> Your User Info component code goes here </>;
};
Reference
Upvotes: 1