Fetching multiple items in React/Redux causing infinite loop and no jsx on screen? - javascript

Goal:
I want to be able to fetch multiple profiles from an array and list them out on the screen. Something like:
John, Sandy, Drew
I am using react and trying to list out users from a friendRequest array. This array is filled with user id's and I want to map over them to get the user and show him/her on the screen.
What is happening is that in the console.log(pendingFriend), it is a infinite loop of in this case two profiles over and over again getting logged. Also no jsx is being displayed on the screen.
Here is the code.
Look in the render > return > where you see the currentUser.friendRequests being mapped over.
import React, { Component } from 'react';
import { connect } from 'react-redux';
import swal from 'sweetalert';
import actions from '../../actions';
import { UpdateProfile } from '../view';
import { DateUtils } from '../../utils';
class Profile extends Component {
constructor() {
super();
this.state = {
profile: {
image:
'https://lh3.googleusercontent.com/EJf2u6azJe-TA6YeMWpDtMHAG6u3i1S1DhbiUXViaF5Pyg_CPEOCOEquKbX3U-drH29oYe98xKJiWqYP1ZxPGUQ545k',
bannerImage:
'https://lh3.googleusercontent.com/RAdfZt76XmM5p_rXwVsfQ3J8ca9aQUgONQaXSE1cC0bR0xETrKAoX8OEOzID-ro_3vFfgO8ZMQIqmjTiaCvuK4GtzI8',
firstName: 'First Name',
lastName: 'Last Name',
email: 'Contact Email',
bio: 'Bio will go here'
}
};
this.deleteProfile = this.deleteProfile.bind(this);
}
componentDidMount() {
const { id } = this.props.match.params;
if (this.props.profiles[id] != null) {
return;
}
this.props
.getProfile(id)
.then(() => {})
.catch(err => {
console.log(err);
});
}
createUpdatedProfile(params) {
const { id } = this.props.match.params;
const profile = this.props.profiles[id];
const { currentUser } = this.props.user;
if (currentUser.id !== profile.id) {
swal({
title: 'Oops...',
text: 'You do not own this profile',
icon: 'error'
});
return;
}
this.props
.updateProfile(currentUser, params)
.then(response => {
swal({
title: `${response.username} Updated!`,
text: 'Thank you for updating your profile',
icon: 'success'
});
})
.catch(err => {
console.log(err);
});
}
deleteProfile() {
const { id } = this.props.match.params;
const profile = this.props.profiles[id];
const { currentUser } = this.props.user;
if (currentUser.id !== profile.id) {
swal({
title: 'Oops...',
text: 'You do not own this profile',
icon: 'error'
});
return;
}
swal({
closeOnClickOutside: false,
closeOnEsc: false,
title: 'Are you sure?',
text:
'All data related to profile will be deleted as well with the profile! If you wish to delete your profile you must type DELETE',
icon: 'warning',
dangerMode: true,
buttons: true,
content: 'input'
}).then(value => {
if (value === 'DELETE') {
const userPosts = this.props.post.all.filter(p => p.profile.id === profile.id);
const userReplies = this.props.reply.all.filter(r => r.user.id === profile.id);
userPosts.map(post => {
this.props.deleteRecord(post);
});
userReplies.map(reply => {
this.props.deleteReply(reply);
});
this.props
.deleteProfile(profile)
.then(data => {
return this.props.logoutUser();
})
.then(data => {
this.props.history.push('/');
swal('Deleted!', 'Your Profile has been deleted.', 'success');
return null;
})
.catch(err => {
console.log(err);
});
}
swal({
title: 'Profile not deleted',
text: 'Make sure you type "DELETE" with caps',
icon: 'error'
});
});
}
addFriend() {
const { id } = this.props.match.params;
const profile = this.props.profiles[id];
const { currentUser } = this.props.user;
if (currentUser == null || profile == null) {
swal({
title: 'Oops...',
text: 'Must be logged in, and user must exist',
icon: 'error'
});
return;
}
const friendRequests = profile.friendRequests || [];
const params = {};
friendRequests.push(currentUser.id);
params.friendRequests = friendRequests;
this.props
.updateProfile(profile, params)
.then(() => {
swal({
title: 'Success',
text: 'Friend Request Sent',
icon: 'success'
});
})
.catch(err => {
console.log(err);
});
}
render() {
const { id } = this.props.match.params;
const profile = this.props.profiles[id];
const { currentUser } = this.props.user;
const defaultProfile = this.state.profile;
const bannerUrl =
profile == null
? defaultProfile.bannerImage
: profile.bannerImage || defaultProfile.bannerImage;
const bannerStyle = {
backgroundImage: `url(${bannerUrl})`,
backgroundSize: '100%',
backgroundRepeat: 'no-repeat',
backgroundPosition: 'center'
};
const nameStyle = {
background: 'rgba(255, 255, 255, 0.7)',
borderRadius: '8px'
};
const imageStyle = {
maxHeight: '150px',
margin: '20px auto'
};
return (
<div>
{profile == null ? (
<div>
<h1>Profile no longer exists</h1>
</div>
) : (
<div>
{currentUser == null ? null : currentUser.id !== profile.id ? null : (
<div className="list-group">
{currentUser.friendRequests
? currentUser.friendRequests.map(request => {
this.props
.getProfile(request)
.then(pendingFriend => {
console.log(pendingFriend);
return (
<div key={pendingFriend.id} className="list-group-item">
<p>{pendingFriend.username}</p>
</div>
);
})
.catch(err => {
console.log(err);
});
})
: null}
</div>
)}
<div className="jumbotron jumbotron-fluid" style={bannerStyle}>
<div className="container" style={nameStyle}>
<img
src={profile.image || defaultProfile.image}
style={imageStyle}
className="rounded img-fluid mx-auto d-block"
/>
</div>
</div>
<div className="row">
<div className="col-sm-12">
<h1 className="display-3 text-center">{profile.username}</h1>
<p className="lead text-center">
{profile.firstName || defaultProfile.firstName}{' '}
{profile.lastName || defaultProfile.lastName}
</p>
<p className="lead text-center text-muted">
{profile.email || defaultProfile.email}
</p>
<p className="text-center text-muted">
Became a User: {DateUtils.relativeTime(profile.timestamp)}
</p>
<hr className="my-4" />
<p className="lead" style={{ border: '1px solid #e6e6e6', padding: '20px' }}>
{profile.bio || defaultProfile.bio}
</p>
</div>
</div>
{currentUser == null ? null : currentUser.id !== profile.id ? (
<div className="row justify-content-center" style={{ marginBottom: '100px' }}>
<div className="col-sm-6">
{profile.friendRequests ? (
profile.friendRequests.indexOf(currentUser.id) === -1 ? (
<button
className="btn btn-primary btn-lg btn-block"
onClick={this.addFriend.bind(this)}
>
Add Friend
</button>
) : (
<button className="btn btn-success btn-lg btn-block">
Pending Friend Request
</button>
)
) : (
<button
className="btn btn-primary btn-lg btn-block"
onClick={this.addFriend.bind(this)}
>
Add Friend
</button>
)}
</div>
</div>
) : (
<div>
<UpdateProfile
currentProfile={profile}
onCreate={this.createUpdatedProfile.bind(this)}
/>
<div className="row justify-content-center" style={{ marginBottom: '100px' }}>
<div className="col-sm-6">
<button
className="btn btn-danger btn-lg btn-block"
onClick={this.deleteProfile}
>
DELETE Profile
</button>
</div>
</div>
</div>
)}
</div>
)}
</div>
);
}
}
const stateToProps = state => {
return {
profiles: state.profile,
user: state.user,
post: state.post,
reply: state.reply
};
};
const dispatchToProps = dispatch => {
return {
getProfile: id => dispatch(actions.getProfile(id)),
updateProfile: (entity, params) => dispatch(actions.updateProfile(entity, params)),
deleteProfile: entity => dispatch(actions.deleteProfile(entity)),
deleteRecord: entity => dispatch(actions.deleteRecord(entity)),
deleteReply: entity => dispatch(actions.deleteReply(entity)),
logoutUser: () => dispatch(actions.logoutUser())
};
};
const loadData = store => {
return store.dispatch(actions.getProfile(this.props.match.params.id));
};
export default {
loadData: loadData,
component: connect(stateToProps, dispatchToProps)(Profile)
};

Your code is breaking the pattern in so many ways, i'm not sure where to start :)
First of all as for your question about the infinite loop, you
probably want to start with this line in your render method:
this.props.getProfile(request)
.then(pendingFriend => {
console.log(pendingFriend);
You should never ever update the state or dispatch actions.
These are the two main ways to re-render a component, state change
and new props. When you dispatch an action you actually causing a
new render call as a new prop will be received to your connected
component. With that said, do not do async calls inside the
render method, render method should be pure with no side effects.
Async calls and data fetching should be triggered in
componentDidMount.
Another thing not related to your problem directly, most of your
handlers are not bind the this object to the class, the only
handler you did bind is deleteProfile. bind them all or use
arrow functions which will use the this in a lexical context.
Again, not related directly to your problem, always pass props when
using the constructor and super:
constructor(props) {
super(props);
Edit
As a followup to your comment:
is it okay if I directly bind the functions like
this.deleteProfile.bind(this) instead of doing this.deleteProfile =
this.deleteProfile.bind(this) in the constructor just do
this.deleteProfile.bind(this) inside the render method
This won't change anything as bind isn't mutating the function, instead it returns a new instance with the this object is attached to it (it uses call behind the scenes) you can see the implementation.
So you must override your handlers with the new instance.
By the way, inside your render function, doing binding or any other operation that will create a new instance of a function or object is less preferable as you will create new instance on each render call of course. if you can "lift" it up to a method like the constructor (which is called only once in a component's life time) is much more performant.

Related

Proper react component not showing based on the type of user

I am having some issues in displaying a separate component based on the type of user.
Detailed Explanation of what I am trying to achieve:
The code snippet where I am having issues is as follows:
const addDataRequest = this.state.addDataRequestVisible ? (
<div className="main-page-section">
<Growl ref={this.growl}/>
{isAdmin(user)? (
<AdminDataRequestEnhancedForm handleSubmit={this.handleSubmit} addProject={this.addProjectOpen} onCancel={this.handleCancel}/>
) : (
<DataRequestEnhancedForm handleSubmit={this.handleSubmit} addProject={this.addProjectOpen} onCancel={this.handleCancel}/>
)
}
</div>
) : null;
Right now, DataRequestFormJS andAdminDataRequestForm are exact same forms as far as form content is concerned. So based on the user role, if it's an Admin, I want to display AdminDataRequestEnhancedForm component and if
it's not an Admin, I want to display DataRequestEnhancedForm component. But even though, I have specific checks for isAdmin in place, as shown in the code snippet above, it's not displaying AdminDataRequestEnhancedForm component
for an Admin user. I am wondering what's wrong I am doing? Does it have something to do with the state variable -this.state.addDataRequestVisible?
Here is the complete code:
import {DataRequestEnhancedForm} from "./DataRequestFormJS";
import {AdminDataRequestEnhancedForm} from "./AdminDataRequestForm";
import {isAdmin} from './auth';
class DataRequest extends React.Component<any, any> {
private growl = React.createRef<Growl>();
constructor(props) {
super(props);
this.state = {
result: '',
addDataRequestVisible: false,
addProjectVisible: false,
//For admin specific
addAdminDataRequestVisible: false,
addAdminProjectVisible: false
};
this.handleSubmit = this.handleSubmit.bind(this)
this.handleCancel = this.handleCancel.bind(this)
this.addProjectOpen = this.addProjectOpen.bind(this)
this.addProjectClose = this.addProjectClose.bind(this)
}
handleSubmit = (values) => {
let responseData = []
axios.post('upms/saveData', {
}).then((response) => {
console.log('response', response)
responseData = response.data
this.setState({
addDataRequestVisible: false,
dataRequestFormVisible: false,
dataRequestGridVisible: true,
selectedDataRequest: []
}, () => {
this.growl.current.show({
severity: 'success',
summary: 'Save Successful',
detail: 'Data Request has been created'
})
})
}).catch((err) => {
this.growl.current.show({
severity: 'error',
summary: 'Save Unsuccessful',
detail: 'Could not add Data Request'
})
})
}
handleCancel = event => {
console.log('In handleCancel....')
if (event) {
this.setState({ addDataRequestVisible: false})
}
}
addProjectOpen = event =>{
if (event) {
this.setState({ addProjectVisible: true})
}
}
addProjectClose = event =>{
console.log('In addProjectClose....' + event)
if (event) {
this.setState({ addProjectVisible: false})
}
}
render() {
const user = JSON.parse(sessionStorage.getItem('loggedInUser'))
let url = isAdmin(user) ? 'url1' : 'api/personnels/' + user.id + '/url2'
const defaultView = this.state.addDataRequestVisible?null: (
<div className="data-request-main-section">
<Growl ref={this.growl}/>
<div className="page-title-section">
<Button label="New Data Request" icon="pi pi-plus" className="new-data-req-btn"
onClick={(e) => this.setState({ addDataRequestVisible: true})}/>
</div>
<DataRequestsDataTable url={url} handleSubmit={this.handleSubmit}/>
</div>
)
const addDataRequest = this.state.addDataRequestVisible ? (
<div className="main-page-section">
<Growl ref={this.growl}/>
{isAdmin(user)? (
<AdminDataRequestEnhancedForm handleSubmit={this.handleSubmit} addProject={this.addProjectOpen} onCancel={this.handleCancel}/>
) : (
<DataRequestEnhancedForm handleSubmit={this.handleSubmit} addProject={this.addProjectOpen} onCancel={this.handleCancel}/>
)
}
</div>
) : null;
const addProjectDialog = this.state.addProjectVisible ? (
<Dialog visible={true} modal={true} className="add-project-popup"
onHide={() => this.setState({addProjectVisible: false})}>
<div style={{textAlign: 'center'}}>
<h3>Add New Project</h3>
<AddNewProjectForm closeProject={this.addProjectClose} />
</div>
</Dialog>
) : null
return (
<div className="datareq-page">
{defaultView}
{addDataRequest}
{addProjectDialog}
</div>
);
}
}
export default DataRequest
My auth.js looks like following:
export const isAdmin = (user) => {
return JSON.parse(sessionStorage.assignees).some(assignee => assignee.id === user.id)
}
It seems like your function isAdmin doesn't return the result directly and by the time it finishes executing DataRequestEnhancedForm will have been rendered instead. Try making that isAdmin function asynchronous like this:
export const isAdmin = async (user) => {
let userType = await JSON.parse(sessionStorage.assignees).some(assignee => assignee.id === user.id)
return userType
}

React/axios Fetch data before rendering

I'm working on a react app and I'm trying to fetch data before the rendering. I have tried a lot of solution available on the NET but nothing seems to work.
I'm trying to fetch datas from my nodeJS server, (the files from the services folder so I can manage them, add them etc..)
import React, {Component} from 'react';
import Checkbox from './Checkbox';
import axios from 'axios';
const OPTIONS = [];
console.log('dd');
class App extends Component {
state = {
checkboxes: OPTIONS.reduce(
(options, option) => ({
...options,
[option]: false,
}),
{}
),
load: true,
};
componentWillMount() {
this.callF();
this.setState({load: false});
}
selectAllCheckboxes = (isSelected) => {
Object.keys(this.state.checkboxes).forEach((checkbox) => {
this.setState((prevState) => ({
checkboxes: {
...prevState.checkboxes,
[checkbox]: isSelected,
},
}));
});
};
callF = () => {
console.log('Yes');
axios
.get('http://localhost:3007/service')
.then(function (response) {
response.data.forEach((element) => {
if (OPTIONS.indexOf(element) === -1 && element !== 'Master.js' && element !== 'command.txt') {
OPTIONS.push(element);
}
});
console.log('----' + OPTIONS);
})
.catch(function (error) {
console.log('{' + error + '}');
});
};
selectAll = () => {
this.selectAllCheckboxes(true);
console.log('HEY');
};
deselectAll = () => this.selectAllCheckboxes(false);
handleCheckboxChange = (changeEvent) => {
const {name} = changeEvent.target;
this.setState((prevState) => ({
checkboxes: {
...prevState.checkboxes,
[name]: !prevState.checkboxes[name],
},
}));
};
handleFormSubmit = (formSubmitEvent) => {
formSubmitEvent.preventDefault();
Object.keys(this.state.checkboxes)
.filter((checkbox) => this.state.checkboxes[checkbox])
.forEach((checkbox) => {
console.log(checkbox, 'is selected.');
});
};
createCheckbox = (option) => (
<Checkbox
label={option}
isSelected={this.state.checkboxes[option]}
onCheckboxChange={this.handleCheckboxChange}
key={option}
/>
);
createCheckboxes = () => {
console.log('|||' + OPTIONS);
OPTIONS.map(this.createCheckbox);
};
render() {
const {load} = this.state;
if (!load) {
return null;
}
return (
<div className="container">
<div className="row mt-5">
<div className="col-sm-12">
<form onSubmit={this.handleFormSubmit}>
{this.createCheckboxes()}
<ul>{OPTIONS}</ul>
<div className="form-group mt-2">
<button type="button" className="btn btn-outline-primary mr-2" onClick={this.selectAll}>
Select All
</button>
<button type="button" className="btn btn-outline-primary mr-2" onClick={this.deselectAll}>
Deselect All
</button>
<button
type="submit"
className="btn btn-primary"
onClick={() => {
this.forceUpdate();
}}>
reload
</button>
</div>
</form>
</div>
</div>
</div>
);
}
}
export default App;
I tried calling props, using componentWillMount and ComponentDidMount but well I'm not good at this I guess.
Since you have mentioned that you need to fetch data BEFORE rendering, I'm guessing that you are getting the data, but after rendering.
In this cases please consider conditional rendering.
For example, add a new state which will keep loading status. Set it to true initially. When you fetched something - set the loading to false.
And based on the loading status (when it's false) you can render everything you need.
EDIT:
You are not updating your loading status when fetched - please remove quotes:
You have - this.setState({'load': false});
Try this.setState({load: false});

Action being callled but not hitting

I am using MERN stack and redux, i have created a findOneAndUpdate api and tested it on Postman. All works as it should but i can't get it working on my website. It never actually hits the updateSubject action. Am i passing in the data incorrectly? Anyone any idea what i am missing?
action
export const updateSubject = (id, rate, noOfVotes, rating) => (dispatch) => {
console.log("updateSubject hitting");
fetch(`/api/subjects/Subject/${id}/${rate}/${noOfVotes}/${rating}`)
.then((res) => res.json())
.then((subject) =>
dispatch({
type: UPDATE_SUBJECT,
subjects: subject,
})
);
};
api
// update subject
subjectRouter.put("/subject/:_id/:rate/:noOfVotes/:rating", (req, res) => {
Subject.findOneAndUpdate(
{ _id: req.params._id },
{
rating: Number(req.params.rating) + Number(req.params.rate),
noOfVotes: Number(req.params.noOfVotes) + 1,
},
{
new: true,
useFindAndModify: false,
}
)
.then((subjects) => res.json(subjects))
.catch((err) => console.log(err));
});
component
import React, { Component } from "react";
import PropTypes from "prop-types";
import GoogleSearch from "./GoogleSearch";
import { connect } from "react-redux";
import { fetchSubjects } from "../../actions/subject";
import { fetchComments } from "../../actions/comment";
import { updateSubject } from "../../actions/subject";
class Subject extends Component {
// on loading the subjects and comments
// are fetched from the database
componentDidMount() {
this.props.fetchSubjects();
this.props.fetchComments();
}
constructor(props) {
super(props);
this.state = {
// set inital state for subjects description
// and summary to invisible
viewDesription: -1,
viewSummary: -1,
comments: [],
};
}
componentWillReceiveProps(nextProps) {
// new subject and comments are added to the top
if (nextProps.newPost) {
this.props.subjects.unshift(nextProps.newPost);
}
if (nextProps.newPost) {
this.props.comments.unshift(nextProps.newPost);
}
}
clickHandler = (id) => {
// when a subject title is clicked pass in its id
// and make the desciption visible
const { viewDescription } = this.state;
this.setState({ viewDescription: viewDescription === id ? -1 : id });
// add relevant comments to the state
var i;
var temp = [];
for (i = 0; i < this.props.comments.length; i++) {
if (this.props.comments[i].subject === id) {
temp.unshift(this.props.comments[i]);
}
}
this.setState({
comments: temp,
});
// save the subject id to local storage
// this is done incase a new comment is added
// then the subject associated with it can be retrieved
// and added as a property of that comment
localStorage.setItem("passedSubject", id);
};
// hovering on and off subjects toggles the visibility of the summary
hoverHandler = (id) => {
this.setState({ viewSummary: id });
};
hoverOffHandler = () => {
this.setState({ viewSummary: -1 });
};
rateHandler = (id, rate) => {
var currRate;
var currVotes;
var i;
for (i = 0; i < this.props.subjects.length; i++) {
if (this.props.subjects[i]._id === id) {
currRate = this.props.subjects[i].rating;
currVotes = this.props.subjects[i].noOfVotes;
}
}
updateSubject(id, rate, currVotes, currRate);
console.log(id, rate, currVotes, currRate);
};
findAuthor(id) {
// search users for id return name
}
render() {
const subjectItems = this.props.subjects.map((subject) => {
// if the state equals the id set to visible if not set to invisible
var view = this.state.viewDescription === subject._id ? "" : "none";
var hover = this.state.viewSummary === subject._id ? "" : "none";
var comments = this.state.comments;
return (
<div key={subject._id}>
<div
className="subjectTitle"
onClick={() => this.clickHandler(subject._id)}
onMouseEnter={() => this.hoverHandler(subject._id)}
onMouseLeave={() => this.hoverOffHandler()}
>
<p className="title">{subject.title}</p>
<p className="rate">
Rate this subject:
<button onClick={() => this.rateHandler(subject._id, 1)}>
1
</button>
<button onClick={() => this.rateHandler(subject._id, 2)}>
2
</button>
<button onClick={() => this.rateHandler(subject._id, 3)}>
3
</button>
<button onClick={() => this.rateHandler(subject._id, 4)}>
4
</button>
<button onClick={() => this.rateHandler(subject._id, 5)}>
5
</button>
</p>
<p className="rating">
Rating: {(subject.rating / subject.noOfVotes).toFixed(1)}/5
</p>
<p className="summary" style={{ display: hover }}>
{subject.summary}
</p>
</div>
<div className="subjectBody " style={{ display: view }}>
<div className="subjectAuthor">
<p className="author" style={{ fontWeight: "bold" }}>
Subject created by: {subject.author} on {subject.date}
</p>
</div>
<div className="subjectDescription">
<p className="description">{subject.description}</p>
</div>
<div className="subjectLinks">Links:</div>
<div className="subjectComments">
<p style={{ fontWeight: "bold" }}>Comments:</p>
{comments.map((comment, i) => {
return (
<div key={i} className="singleComment">
<p>
{comment.title}
<br />
{comment.comment}
<br />
Comment by : {comment.author}
</p>
</div>
);
})}
<a href="/addcomment">
<div className="buttonAddComment">ADD COMMENT</div>
</a>
</div>
</div>
</div>
);
});
return (
<div id="Subject">
<GoogleSearch />
{subjectItems}
</div>
);
}
}
Subject.propTypes = {
fetchSubjects: PropTypes.func.isRequired,
fetchComments: PropTypes.func.isRequired,
subjects: PropTypes.array.isRequired,
comments: PropTypes.array.isRequired,
newPost: PropTypes.object,
};
const mapStateToProps = (state) => ({
subjects: state.subjects.items,
newSubject: state.subjects.item,
comments: state.comments.items,
newComment: state.comments.item,
});
// export default Subject;
export default connect(mapStateToProps, { fetchSubjects, fetchComments })(
Subject,
Comment
);
You are not attaching the updateSubject to the component itself, currently you only have fetchSubjects and fetchComments instead.
So, you would need to change your connect function like so:
export default connect(mapStateToProps, { fetchSubjects, fetchComments, updateSubject })(
Subject,
Comment
);
and then your calling function could be changed like so:
rateHandler = (id, rate) => {
const subject = this.props.subjects.find( subject => subject._id === id);
// when no subject was found, the updateSubject won't be called
subject && this.props.updateSubject( id, rate, subject.noOfVotes, subject.rating );
};
This would also mean that you should update your proptypes like:
Subject.propTypes = {
fetchSubjects: PropTypes.func.isRequired,
fetchComments: PropTypes.func.isRequired,
updateSubject: PropTypes.func.isRequired,
subjects: PropTypes.array.isRequired,
comments: PropTypes.array.isRequired,
newPost: PropTypes.object,
};
As you mentioned in the comments, you are using a put endpoint, so you should probably update your updateSubject method to the following
export const updateSubject = (id, rate, noOfVotes, rating) => (dispatch) => {
console.log("updateSubject hitting");
fetch(`/api/subjects/Subject/${id}/${rate}/${noOfVotes}/${rating}`, { method: 'PUT' })
.then((res) => res.json())
.then((subject) =>
dispatch({
type: UPDATE_SUBJECT,
subjects: subject,
})
);
};

createStore not changing from initial state to Action proved value

Im trying to get access a variable called isSuperAdmin, It basically tells me if the logged in user is a super admin or not allowing me to disable some features.
I currently have no access to the variable in the current page however my redux action is showing it as being there, I think I may have configured something incorrectly, as of now my code doesn't change from the initial state value of null to the bool value isSuperUser. Here is the page that I am trying to use this variable.
import React, { PropTypes } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import { connect } from 'react-redux';
import Modal from '../Modal';
import Summary from '../Summary';
import s from './BookingDetailsModal.scss';
import AmendConsumerDetails from './AmendConsumerDetails';
import ChangeBookingSession from './ChangeBookingSession';
import payReservationCashActionCreator from '../../actions/payReservationCash';
import payReservationCardActionCreator from '../../actions/payReservationCard';
import payRestActionCreator from '../../actions/payRest';
import refundCashActionCreator from '../../actions/refundCash';
import cancelReservationActionCreator from '../../actions/cancelReservation';
import formatPrice from '../../../../../core/formatPrice';
import {
BOXOFFICE_HIDE_BOOKING_DETAILS,
BOXOFFICE_SET_BOOKING_DETAILS_ACTION_TYPE,
resendConfirmationEmail as resendConfirmationEmailActionCreator,
} from '../../actions';
function renderActionButtons({
isSuperAdmin,
setActionType,
resendConfirmationEmail,
order: {
type: orderType,
paid: orderPaid,
amount: orderAmount,
refundedAt: orderRefundedAt,
canceledAt: orderCanceledAt,
sessionId,
},
isCreatingPayment,
payReservationCard,
payReservationCash,
payRest,
refundCash,
cancelReservation,
}) {
debugger;
return (
<div className={s.buttonsContainer}>
<div className={s.buttonsContainer}>
<div className={s.buttonContainer}>
<button
onClick={(e) => {
e.preventDefault();
setActionType('AMEND_CONSUMER_DETAILS');
}}
>Amend consumer details</button>
</div>
{ sessionId ?
<div className={s.buttonContainer}>
<button
onClick={(e) => {
e.preventDefault();
setActionType('CHANGE_SESSION');
}}
>Move to another session</button>
</div> : null
}
<div className={s.buttonContainer}>
<button disabled>Amend tickets or products</button>
</div>
{ orderType === 'reservation' && isCreatingPayment && !orderPaid ?
<div>
<div className={s.buttonContainer}>
<button
onClick={(e) => {
e.preventDefault();
payReservationCash();
}}
>Pay Reservation CASH</button>
</div>
<div className={s.buttonContainer}>
<button
onClick={(e) => {
e.preventDefault();
payReservationCard();
}}
>Pay Reservation CARD</button>
</div>
</div> :
null
}
{ orderType === 'deposit' && isCreatingPayment && !orderPaid ?
<div>
<div className={s.buttonContainer}>
<button
onClick={(e) => {
e.preventDefault();
payRest('CASH');
}}
>Pay Rest CASH</button>
</div>
<div className={s.buttonContainer}>
<button
onClick={(e) => {
e.preventDefault();
payRest('CARD');
}}
>Pay Rest CARD</button>
</div>
</div> :
null
}
{ !orderRefundedAt && orderPaid ?
<div className={s.buttonContainer}>
<button
disabled={isSuperAdmin}
onClick={(e) => {
e.preventDefault();
refundCash(orderAmount);
}}
>Refund CASH, {formatPrice(orderAmount)}</button>
</div> : null
}
{ orderCanceledAt === null && orderType === 'reservation' ?
<div className={s.buttonContainer}>
<button
onClick={(e) => {
e.preventDefault();
cancelReservation();
}}
>Cancel Reservation</button>
</div> : null
}
<div className={s.buttonContainer}>
<button
onClick={(e) => {
e.preventDefault();
resendConfirmationEmail();
}}
>Resend confirmation email</button>
</div>
</div>
</div>
);
}
renderActionButtons.propTypes = {
isSuperAdmin: PropTypes.bool.isRequired,
setActionType: PropTypes.func.isRequired,
resendConfirmationEmail: PropTypes.func.isRequired,
order: PropTypes.shape({
type: PropTypes.string.isRequired,
paid: PropTypes.bool.isRequired,
sessionId: PropTypes.string.isRequired,
amount: PropTypes.number.isRequired,
// reservationPaidCashAt: PropTypes.string.isRequired,
// reservationPaidCardAt: PropTypes.string.isRequired,
}).isRequired,
payReservationCard: PropTypes.func.isRequired,
payReservationCash: PropTypes.func.isRequired,
payRest: PropTypes.func.isRequired,
isCreatingPayment: PropTypes.bool.isRequired,
refundCash: PropTypes.func.isRequired,
cancelReservation: PropTypes.func.isRequired,
};
const components = {
AMEND_CONSUMER_DETAILS: AmendConsumerDetails,
CHANGE_SESSION: ChangeBookingSession,
};
function renderAction(actionType, props) {
const Component = components[actionType];
return <Component {...props} />;
}
function BookingDetailsModal(props) {
const { hideOrderDetails, orderId, bookingDetailsActionType } = props;
return (
<Modal onClose={hideOrderDetails}>
<div className={s.container}>
<div className={s.summaryContainer}>
<Summary orderId={orderId} withEdits={false} />
</div>
<div className={s.actionsContainer}>
{bookingDetailsActionType ?
renderAction(bookingDetailsActionType, props) :
renderActionButtons(props)
}
</div>
</div>
</Modal>
);
}
BookingDetailsModal.propTypes = {
orderId: PropTypes.string.isRequired,
hideOrderDetails: PropTypes.func.isRequired,
bookingDetailsActionType: PropTypes.oneOf([
'AMEND_CONSUMER_DETAILS',
]),
};
const mapStateToProps = (state, { orderId }) => (
{
ui: { bookingDetailsActionType },
ui: { isSuperAdmin },
orders: {
data: { [orderId]: order },
edits: { [orderId]: orderEdits },
},
}
) => ({
bookingDetailsActionType,
isSuperAdmin,
order,
isCreatingPayment: orderEdits.isCreatingPayment,
});
const mapDispatchToProps = (dispatch, { orderId }) => ({
hideOrderDetails: () => dispatch({ type: BOXOFFICE_HIDE_BOOKING_DETAILS }),
setActionType: actionType =>
dispatch({ type: BOXOFFICE_SET_BOOKING_DETAILS_ACTION_TYPE, actionType }),
resendConfirmationEmail: () => dispatch(resendConfirmationEmailActionCreator(orderId)),
payReservationCard: () => dispatch(payReservationCardActionCreator(orderId)),
payReservationCash: () => dispatch(payReservationCashActionCreator(orderId)),
payRest: type => dispatch(payRestActionCreator(orderId, type)),
refundCash: amount => dispatch(refundCashActionCreator(orderId, amount)),
cancelReservation: () => dispatch(cancelReservationActionCreator(orderId)),
});
export default connect(mapStateToProps, mapDispatchToProps)(withStyles(s)(BookingDetailsModal));
My Redux tab on page load shows the following:
type(pin): "BOXOFFICE_IS_SUPER_USER"
isSuperAdmin(pin): true
This is how I have used createStore to access the variable:
const isSuperAdmin = createStore(null, {
[BOXOFFICE_IS_SUPER_USER]: isSuperAdmin => isSuperAdmin,
});
I then proceeded to add it to the reducer at the bottom.
edit I have changed the variable isSuperAdmin in the createStore to true and this can be read perfectly fine, it must now be an issue with the variable passed to the action in the first place.
Here is the code where I get the value of the variable and pass it on:
Export default ({ knex }) => authenticateAdmin(knex)(
async (req, res) => {
try {
const { eventId } = req;
const event = await fetchEvent(knex, eventId);
const isSuperAdmin = await res.isSuperAdmin;
res.send({ event, isSuperAdmin});
} catch (err) {
res.send(err.stack);
console.error(err.stack); // eslint-disable-line no-console
throw err;
}
}
);
And the dispatch:
export const fetchEvent = () => async (dispatch, getState) => {
try {
const state = getState();
const { auth: { password } } = state;
const response = await fetch('/api/event', {
headers: {
Accept: 'application-json',
'X-Password': password,
},
});
if (response.status === 200) {
const { event, isSuperAdmin } = await response.json();
dispatch({ type: BOXOFFICE_SET_EVENT, event });
dispatch({ type: BOXOFFICE_IS_SUPER_USER, isSuperAdmin });
} else {
localStorage.removeItem('password');
dispatch({ type: BOXOFFICE_UNAUTHENTICATE });
}
} catch (err) {
console.log(err); // eslint-disable-line no-console
throw err;
}
};
EDIT
Here is the reducer:
export default combineReducers({
isSuperAdmin, ------- My variable
isProcessingPayment,
isSelectDateCollapsed,
isLoadingBookings,
shouldShowBookings,
shouldShowDepositModal,
shouldShowReservationModal,
shouldShowConsumerDetailsModal,
shouldShowDiscountModal,
shouldShowOrderConfirmationModal,
bookingFilter,
selectedOrderId,
sendConfirmationEmail,
bookingIds,
orderDetailsId,
bookingDetailsActionType,
});
I guess the way you defined your mapStateToProps is incorrect.
Updated the code
try following:
const mapStateToProps = ({
ui: {
bookingDetailsActionType,
isSuperAdmin
},
orders: {
data,
edits
}
}, {
orderId
}) => {
const order = data[orderId],
orderEdits = edits[orderId];
return {
bookingDetailsActionType,
isSuperAdmin,
order,
isCreatingPayment: orderEdits.isCreatingPayment
};
};
I finally have a solution! Turns out my issue was not setting a property type for my isSuperUser variable. Despite my colleague telling me that it will work without any property type (which still makes sense to me and confuses me as to why it wont work?!).
A simple change in the index.js file from:
[BOXOFFICE_IS_SUPER_USER]: isSuperAdmin => isSuperAdmin,
to
[BOXOFFICE_IS_SUPER_USER]: (state, { isSuperAdmin }) => isSuperAdmin,
and adding a property type to the show.js file where I used res.send()
res.send({ event, isSuperAdmin: isSuperAdmin});
Im still at a loss as to why it won't work with no property type but oh well...!

Getting error TypeError: Cannot read property 'id' of undefined using React/Redux action

I am using react/redux and the error is happening after a deleteRequest is called using an action. The reducer removes the item from the array and I think that is why this is happening, but I should be changing the location so it should not be rendering this page anymore.
The direct error is coming from the Post component down below from the this.props.deleteRecord in the catch block.
I am also using turbo which is how I make the deleteRequest and store the data. If you need a reference here is the docs. https://www.turbo360.co/docs
Reducer:
import constants from '../constants';
const initialState = {
all: null
};
export default (state = initialState, action) => {
switch (action.type) {
case constants.POST_CREATED:
return {
...state,
all: state.all.concat(action.data),
[action.data.id]: action.data
};
case constants.RECORD_UPDATED:
return {
...state,
[action.data.id]: action.data,
all: all.map(item => (item.id === action.data.id ? action.data : item))
};
case constants.RECORD_DELETED:
const newState = {
...state,
all: state.all.filter(item => item.id !== action.data.id)
};
delete newState[action.payload.id];
return newState;
case constants.FETCH_POSTS:
const sortedData = action.data.sort((a, b) => {
return new Date(b.timestamp) - new Date(a.timestamp);
});
return { ...state, all: sortedData };
case constants.FETCH_POST:
return { ...state, [action.data.id]: action.data };
default:
return state;
}
};
Component:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import swal from 'sweetalert2/dist/sweetalert2.all.min.js';
import actions from '../../actions';
import { DateUtils } from '../../utils';
import { Reply } from '../containers';
import { UpdateRecord } from '../view';
class Post extends Component {
constructor() {
super();
this.state = {
editShow: false
};
}
componentDidMount() {
const { id } = this.props.match.params;
if (this.props.posts[id] != null) {
return;
}
this.props
.getRecord(id)
.then(() => {})
.catch(err => {
console.log(err);
});
}
updateRecord(params) {
const { id } = this.props.match.params;
const post = this.props.posts[id];
const { currentUser } = this.props.user;
if (post.profile.id !== currentUser.id) {
swal({
title: 'Oops...',
text: 'Must be owner of post',
type: 'error'
});
return;
}
this.props
.updateRecord(post, params)
.then(response => {
swal({
title: 'Success',
text: `${currentUser.username} Your post has been updated!`,
type: 'success'
});
})
.catch(err => {
console.log(err);
});
}
deleteRecord() {
const { id } = this.props.match.params;
const post = this.props.posts[id];
const { currentUser } = this.props.user;
if (currentUser.id !== post.profile.id) {
swal({
title: 'Oops...',
text: 'Must be owner of post',
type: 'error'
});
return;
}
this.props
.deleteRecord(post)
.then(() => {
this.props.history.push('/');
swal({
title: 'Post Delete',
text: 'Please create a new post',
type: 'success'
});
})
.catch(err => {
console.log(err);
});
}
render() {
const { id } = this.props.match.params;
const post = this.props.posts[id];
const { currentUser } = this.props.user;
if (post == null) {
return <div />;
}
return (
<div>
<div className="jumbotron">
<h1 className="display-3">{post.title}</h1>
<div className="row" style={{ marginBottom: '25px' }}>
<img className="img-fluid mx-auto" src={`${post.image}`} style={{ maxHeight: '400px' }} />
</div>
<p className="lead">{post.text}</p>
<hr className="my-4" />
{post.video == undefined ? null : (
<div className="row justify-content-center">
<div className="col-8">
<div className="lead" style={{ marginBottom: '25px' }}>
<div className="embed-responsive embed-responsive-16by9">
<video style={{ background: 'black' }} width="800" controls loop tabIndex="0">
<source src={post.video} type={post.videoType} />
Your browser does not support HTML5 video.
</video>
</div>
</div>
</div>
</div>
)}
<div className="lead">
<Link to={`/profile/${post.profile.id}`}>
<button className="btn btn-secondary btn-lg">{post.profile.username}</button>
</Link>
<p style={{ marginTop: '10px' }}>{DateUtils.relativeTime(post.timestamp)}</p>
</div>
{currentUser.id !== post.profile.id ? null : (
<div className="row justify-content-end">
<div className="col-md-2">
<button
onClick={() => {
this.setState({ editShow: !this.state.editShow });
}}
className="btn btn-success"
>
Edit
</button>
</div>
<div className="col-md-2">
<button onClick={this.deleteRecord.bind(this)} className="btn btn-danger">
Delete
</button>
</div>
</div>
)}
</div>
{this.state.editShow === false ? null : (
<div>
<UpdateRecord onCreate={this.updateRecord.bind(this)} currentRecord={post} />
</div>
)}
<div>
<Reply postId={post.id} />
</div>
</div>
);
}
}
const stateToProps = state => {
return {
posts: state.post,
user: state.user
};
};
const dispatchToProps = dispatch => {
return {
getRecord: id => dispatch(actions.getRecord(id)),
updateRecord: (entity, params) => dispatch(actions.updateRecord(entity, params)),
deleteRecord: entity => dispatch(actions.deleteRecord(entity))
};
};
export default connect(stateToProps, dispatchToProps)(Post);
Take a look here
case constants.RECORD_DELETED:
const newState = {
...state,
all: state.all.filter(item => item.id !== action.data.id)
};
delete newState[action.payload.id];
return newState;
You are using action.data when filtering, and action.payload when deleting from object

Categories

Resources