Reputation: 17
I have a problem because I want to use a variable to make a url dynamic
I have this Epic called usersEpic.ts that brings the user info by ID
export const readUserById = (action$, state$) =>
action$.pipe(
ofType(READ_USER),
mergeMap((action: { type: string; payload: any }) => {
return requestEpic({
actionType: READ_USER_SUCCESS,
method: 'GET',
url: `http://localhost:3000/users/1`, //HERE I NEED TO IMPORT THE ID TO BE DYNAMIC
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${state$.value.accountReducer.activeUserAccount.accessToken}`
},
})
})
)
I have another page called interns.tsx that render all the users with a map.
import React, { useState, useCallback } from "react";
import { useDispatch, useSelector } from "react-redux";
import { LOAD_USERS } from "../../components/store/reducers/usersReducer";
export default function Users() {
const dispatch = useDispatch();
const users = useSelector((state) => state.usersReducer.users);
React.useEffect(() => {
dispatch({
type: LOAD_USERS,
});
}, []);
return (
<div>
<div className="container">
<h1 className="dataText">Interns</h1>
<div className="center-item">
<div>
<table>
<thead>
<tr>
<th>Number</th>
<th>Name</th>
<th>Lastname</th>
<th>Email</th>
<th>Option</th>
</tr>
</thead>
{users.map((item) => {
let id = item.id;
const url = `http://localhost:3001/users/${id}`;
return (
<tbody>
<tr>
<td>{item.document}</td>
<td>{item.name}</td>
<td>{item.lastname}</td>
<td>{item.email}</td>
<td className="icons">
<a href={url}>
<i className="fas fa-info-circle icon"></i>
</a>
<a href={url}>
<i className="fas fa-user-edit icon"></i>
</a>
<a href="/users/readUser">
<i className="fas fa-power-off icon green"></i>
</a>
</td>
</tr>
</tbody>
);
})}
</table>
</div>
</div>
</div>
</div>
);
}
I want to export the id = item.id variable from interns.tsx to usersEpic.ts to use it as a dynamic value.
If anyone can help me thanks a lot
Upvotes: 1
Views: 629
Reputation: 19843
You can create a click handler to which you can pass the id
and dispatch the action with type READ_USER
and payload having the id
:
function handleUserClick(id) {
dispatch({
type: READ_USER,
payload: { id }, // passing the id in payload
});
}
...
<td className="icons">
<i
className="fas fa-info-circle icon"
onClick={() => handleUserClick(item.id)}
></i>
...
And get the id
form the payload in epic:
export const readUserById = (action$, state$) =>
action$.pipe(
ofType(READ_USER),
mergeMap((action: { type: string; payload: any }) => {
return requestEpic({
actionType: READ_USER_SUCCESS,
method: "GET",
url: `http://localhost:3000/users/${action.payload.id}`, // HERE, reading the id from the payload
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${state$.value.accountReducer.activeUserAccount.accessToken}`,
},
});
})
);
Upvotes: 1