Reputation: 1073
I am newbie in react and redux, trying to fetch data using api, but trying to fetch by id, unfortunately, id
is undefined in redux logger and no result back from server side,
Here is my code
My route <Route path="/admin/:id" component={AdminPage} />
Action
function getAll(id){
return dispatch =>{
dispatch(request(id));
adminService.getAll(id)
.then( admin => {
dispatch(success(admin));
dispatch(alertActions.success('Welcome Back !'));
},error => {
dispatch(failure(error.toString()));
dispatch(alertActions.error(error.toString()));
});
};
function request(id) { return { type: adminConstants.GETALL_REQUEST, id } }
function success(admin) { return { type: adminConstants.GETALL_SUCCESS, admin } }
function failure(error) { return { type: adminConstants.GETALL_FAILURE, error } }
Reducer
export function admin( state={}, action){
switch(action.type){
case adminConstants.GETALL_REQUEST:
return { loading: true, id : action.id };
case adminConstants.GETALL_SUCCESS:
return { items: action.admin };
case adminConstants.GETALL_FAILURE:
return { error: action.error };
default:
return state
}
}
Service
function getAll(id){
const requestOptions = {
method : 'GET',
headers: authHeader()
};
return fetch(`${apiUrl}/admin/${id}`, requestOptions).then(handleResponse)
.then( data => { return data; });
}
AdminPage
class AdminPage extends React.Component{
componentDidMount(){
this.props.dispatch(adminActions.getAll());
}
render(){
const { admin } = this.props;
return(
<div>
<h3> Admin Panel</h3>
{admin.items &&
<ul>
{admin.items.map((data, index) =>
<li key={data.id}>
email id : {data.email},
end date : {data.dateEnd},
customerId : {data.customerId}
</li>
)}
</ul>
}
</div>
);
}
}
function mapStateToProps(state) {
const { admin } = state;
return { admin};
}
const connectedAdminPage = connect(mapStateToProps)(AdminPage);
export { connectedAdminPage as AdminPage };
Link on Home page
<Link to="/admin/5c4f69d5259f7d14434b4cb6">Admin</Link>
Upvotes: 2
Views: 2258
Reputation: 1186
If you're trying to get the 'id' in
Route path="/admin/:id">
then try
console.log("mark1",this.props.match.params.id)
inside 'AdminPage' component. If it works then you can pass it to the dispatcher via the component and use inside your function.
For more documentation try https://reacttraining.com/react-router/web/example/url-params.
If this is not what you were asking comment below and I'll edit accordingly. :)
Edit: So here is the solution for the 'AdminPage'
class AdminPage extends React.Component{
componentDidMount(){
this.props.dispatch(adminActions.getAll(this.props.match.params.id));
}
...
}
Now it should not be undefined in the action, can you confirm?
Upvotes: 1