I am making a workstation assessment website.
I am stuck with an issue I am having.
The modal is my a grandchild component (modal complete questions). I then have a component named questions as a parent and as the parent to that I have Admin Workstations.
Hierachy
1.AdminWorkstations,
2.Questions,
3.Modal,
(this is not full functionality of these components but is just for the use case I am asking for).
1.Parent gets WSAId(just a id).Passes down to questions.
2.Questions passes the modal component this.
3.Modal gets questions using this id.
However the first modal does not display.I have paginated the results of these page if this makes any diffrence.
this is my modal
import "./ViewWorkstationModal.css";
import React, { useState, useEffect } from "react";
import { Modal, DropdownButton, Dropdown } from "react-bootstrap";
function ModalCompletedQuestions(props) {
const [show, setShowState] = useState(0);
const [loadingToken, setLoadingToken] = useState(0);
const [answeredQuestions, setAnsweredQuestions] = useState([{}]);
useEffect(() => {
setLoadingToken(true);
let data = {
WSAId: props.WSAId
};
fetch("/get-completed-questions", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(recordset => recordset.json())
.then(results => {
setAnsweredQuestions(results.recordset);
});
}, []);
function handleClose() {
setShowState(false);
}
function handleShow() {
setShowState(true);
}
return (
<>
<>
<div className="header-container">
<button
className="btn btn-primary"
style={{ float: "right" }}
onClick={handleShow}
>
Response Overview
</button>
</div>
<div>
<Modal
size="lg"
style={{ width: "100%" }}
show={show}
onHide={handleClose}
animation={true}
>
<h3 style={{ textAlign: "center" }}>{props.workStation}</h3>
{answeredQuestions &&
answeredQuestions.map(function(question, index) {
if (
question.QuestionResponse === "Y" ||
question.QuestionResponse === "N"
) {
return (
<>
<div
style={{
backgroundColor: "#E6E6E6",
padding: "1px"
}}
>
<ul>
{" "}
<b> Q :</b>
<div style={{ float: "right" }}>✔️</div>
{question.QuestionWhenAnswered}
</ul>
</div>
</>
);
} else if (question.QuestionResponse === "P") {
return (
<>
<div
style={{
backgroundColor: "#BDBDBD",
padding: "1px"
}}
>
<ul>
<b> Q :</b>
{question.QuestionWhenAnswered}{" "}
<div style={{ float: "right" }}>❌</div>
{/* <br />
<b> S :</b>
{question.SuggestedSoloution} */}
</ul>
</div>
</>
);
}
})}
</Modal>
</div>
</>
</>
);
}
this is my questions component
class Questions extends React.Component {
constructor(props) {
super(props);
console.log(props);
this.state = {
...props,
questionsAccepted: [],
questionsAcceptedCounter: "",
selectedSet: [],
ViewActivityToken: false,
noteToBeAdded: "",
notesFromDB: [],
addNoteToken: false,
answeredQuestions: []
};
}
render() {
if (!this.state.ViewActivity) {
if (!this.state.viewDetails && !this.state.ViewActivityToken) {
console.log(moment.locale());
return (
<div>
<ModalCompletedQuestions
RUId={this.props.RUId}
workStation={this.props.workStation}
WSAId={this.props.WSAId}
/>
<Link
to={{
pathname: "/admin-view-full-user-wsa-responses",
state: {
WSAId: this.props.WSAId
}
}}
>
<button style={{ float: "right" }} className="btn btn-primary">
View Full Details
</button>
</Link>
<br />
<li>
<b>User Id: </b>
{this.props.RUId}
</li>
<li>
<b>Workstation: </b>
{this.props.workStation}
</li>
<li>
<b>Date: </b>
{moment(this.props.date).format("L")}
</li>
<li>
<b>Complete Token: </b>
{this.props.completeToken}
</li>
</div>
);
} else if (this.state.viewDetails && !this.state.ViewActivityToken) {
return (
<div>
<button
style={{ float: "right" }}
onClick={e =>
this.setState({
ViewActivity: false,
viewDetails: false,
ViewActivityToken: false,
addNoteToken: false
})
}
className="btn btn-secondary"
>
Revert
</button>
<br />
<br />
{this.state.selectedSet &&
this.state.selectedSet.map((item, index) => {
return (
<div>
<li>
{" "}
<b>{item.QuestionWhenAnswered}</b>{" "}
</li>
<li>{item.QuestionResponse}</li>
<li>{item.Accepted}</li>
</div>
);
})}
</div>
);
}
} else if (this.state.ViewActivity && !this.state.addNoteToken) {
return (
<>
<button
style={{ float: "right" }}
onClick={e =>
this.setState({
ViewActivity: false,
viewDetails: false,
ViewActivityToken: false,
addNoteToken: false
})
}
className="btn btn-secondary"
>
Revert
</button>
<br />
<li>
<b>User Id: </b>
{this.props.RUId}
</li>
<li>
<b>Workstation: </b>
{this.props.workStation}
</li>
<li>
<b>Date: </b>
{moment(this.props.date).format("DD/MM/YYYY")}
</li>
<li>
<b>Complete Token: </b>
{this.props.completeToken}
</li>
{this.state.notesFromDB &&
this.state.notesFromDB.map((item, index) => {
return (
<div
style={{
backgroundColor: "white",
border: "inset",
borderWidth: "0.2px"
}}
>
<div style={{ float: "right" }}>
{moment(item.CreationTime).format("HH:MM DD/MM/YYYY ")}
</div>
<div>
<b>{`${item.UserStatus} `}</b>
</div>
<div style={{ textAlign: "left" }}>{item.Notes}</div>
</div>
);
})}
<br />
<button
onClick={this.AddNoteBtn}
className="btn btn-primary"
style={{ width: "100%" }}
>
Add Note
</button>
</>
);
}
}
}
How come when the first is clicked the modal appears blank but the rest of the modals are filled with the right data.
Essentially it seems as if though the first modal is not performing the data fetch which is within the modal component.
Any extra information needed let me know but these seem to be the most important for this use case.
Any help is much appreciated.
I completed this by using a condition within the use effect.
useEffect(() => {
setLoadingToken(true);
let data = {
WSAId: props.WSAId
};
fetch("/get-completed-questions", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then(recordset => recordset.json())
.then(results => {
setAnsweredQuestions(results.recordset);
});
}, [PUT YOUR CONDTION HERE]);
I simply just passed my props through so it says every time there is a new props do this.
Related
I have a react component which has some cards, When I click the plus icon in the card, it would expand and show some data for 30sec and then the data will disappear and on click it will reappear again, here is the component
import React from "react";
import { FaPlus } from "react-icons/fa";
import useTimeout from "../../../common/useTimeout";
import { Modal } from "../../../common/Modal";
import { ToggleState } from "../../../common/Toggle";
import { BsSearch } from "react-icons/bs";
import AdvancedFilter from "./AdvancedFilter";
export default function CitiesList({ cities }: { cities: any }): JSX.Element {
const [filter, setFilter] = React.useState("");
const [sortType, setSortType] = React.useState("");
const [selectedCity, setSelectedCity] = React.useState<any | null>(null);
console.log(filter);
const sorted = cities.sort((a: { name: string }, b: { name: any }) => {
const isReversed = sortType === "asc" ? 1 : -1;
return isReversed * a.name.localeCompare(b.name);
});
const onSort = (sortType: React.SetStateAction<string>) => {
console.log("changed");
setSortType(sortType);
};
const [showMeta, setShowMeta] = React.useState(false);
const handleClick = () => setShowMeta(true);
const getSelectedCity = (selectedCity: any) => {
setSelectedCity(selectedCity);
console.log("SELECTED CITY", selectedCity);
};
const [visible, setVisible] = React.useState(true);
const hide = () => setVisible(false);
useTimeout(hide, 30000);
console.log("CITIES", cities);
console.log({ selectedCity });
return (
<div style={{ marginTop: "3rem" }}>
<div
style={{
display: "flex",
justifyContent: "space-between",
alignItems: "center",
marginBottom: "20px",
}}
>
<div>List of cities</div>
<div style={{ display: "flex", alignItems: "center" }}>
<div style={{ marginRight: "1rem" }}>
<ToggleState
render={({ isOpen, open, close }) => {
return (
<>
<button
type="button"
className="btn btn-primary"
onClick={() => {
isOpen ? close() : open();
}}
>
Advanced Filter
</button>
<Modal
isActive={isOpen}
modalContentWidth={"30%"}
header={() => "Advanced Filter"}
close={() => close()}
renderBody={() => {
return <AdvancedFilter close={() => close()} />;
}}
></Modal>
</>
);
}}
/>
</div>
<div style={{ position: "relative", marginRight: "1rem" }}>
<input
type="text"
placeholder="Filter"
name="namePrefix"
style={{ padding: "0.35rem" }}
onChange={(e: any) => {
setFilter(e.target.value);
}}
/>
<div style={{ position: "absolute", top: "5px", right: "5px" }}>
<BsSearch size="16" />
</div>
</div>
<div style={{ width: "8rem" }}>
<div className="btn-group">
<button
type="button"
className="btn dropdown-toggle sort-button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
{sortType === "asc"
? "Ascending"
: sortType === "desc"
? "Descending"
: "Select"}
</button>
<ul className="dropdown-menu sort-button">
<li>
<button
className="dropdown-item"
type="button"
onClick={() => onSort("asc")}
>
Ascending
</button>
</li>
<li>
<button
className="dropdown-item"
type="button"
onClick={() => onSort("desc")}
>
Descending
</button>
</li>
</ul>
</div>
</div>
</div>
</div>
<div>
<div>
<div className="row">
{cities &&
sorted.map((item: any, index: number) => (
<div className="col-lg-3" key={index}>
<div
className="card"
style={{
textAlign: "center",
display: "flex",
justifyContent: "center",
paddingBottom: "1rem",
marginBottom: "1rem",
marginRight: "1rem",
}}
>
<div className="card-body">
<h5 className="card-title">{item.name}</h5>
</div>
{visible && showMeta ? (
<div>
<p>Longitude: {item.longitude}</p>
<p>Latitude: {item.latitude}</p>
<p>Population: {item.population}</p>
{/* <p>Time Zone: America</p> */}
</div>
) : (
<div
onClick={() => {
handleClick();
getSelectedCity(item.id);
}}
style={{ cursor: "pointer" }}
>
<FaPlus size="18" />
</div>
)}
</div>
</div>
))}
</div>
</div>
</div>
<div
style={{ marginTop: "30px", display: "flex", justifyContent: "center" }}
>
{cities && cities.length > 10 ? (
<button className="secondary-button">Load More</button>
) : (
<p>There are no more cities</p>
)}
</div>
</div>
);
}
here is the useTimeout function
import { useEffect, useRef } from "react";
function useTimeout(callback: () => void, delay: number | null) {
const savedCallback = useRef(callback);
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
useEffect(() => {
if (delay === null) {
return;
}
const id = setTimeout(() => savedCallback.current(), delay);
return () => clearTimeout(id);
}, [delay]);
}
export default useTimeout;
Now currently if I click on one card, all the cards opens and also after when the data disappears after 30sec it does not reappear on button click. I need to reload the page to do reappear data again.I need to solve 2 issues here: 1. how can I open one card only at a time on clicking on the icon, 2. how can I reappear data on button click without refreshing the page.
As I understand you, some information is
<p>Longitude: {item.longitude}</p>
<p>Latitude: {item.latitude}</p>
<p>Population: {item.population}</p>
You have global statement of showing this info for all cards. To reduce it, make new component which will have local state of this info:
import React from 'react'
const timeout = 15000
export const CityCard = ({item, visible, getSelectedCity}) => {
const [showMeta, setShowMeta] = React.useState(false)
const handleClick = React.useCallback(()=>{
setShowMeta(true)
setTimeout(()=>{
setShowMeta(false)
},timeout )
}, [showMeta])
return(
<div className="col-lg-3" key={index}>
<div
className="card"
style={{
textAlign: "center",
display: "flex",
justifyContent: "center",
paddingBottom: "1rem",
marginBottom: "1rem",
marginRight: "1rem",
}}
>
<div className="card-body">
<h5 className="card-title">{item.name}</h5>
</div>
{visible && showMeta ? (
<div>
<p>Longitude: {item.longitude}</p>
<p>Latitude: {item.latitude}</p>
<p>Population: {item.population}</p>
{/* <p>Time Zone: America</p> */}
</div>
) : (
<button
onClick={() => {
handleClick();
getSelectedCity(item.id);
}}
type='button'
disabled={showMeta}
style={{ cursor: "pointer" }}
>
<FaPlus size="18" />
</button>
)}
</div>
</div>
)
}
At the end, add this component to the CityList
There is an edit button. that edit button, I want to show the button if those items were created in less than 6 hours. The button should not be shown for more than 6 hours. I use moment js to calculate time. time calculation is working perfectly. but button visibility, not working.
Current time state
timenow:moment().format('H')
This is my condition
{(moment(post.createdAt).add(6,'hour').format('H')< this.state.timenow)||(
<Button
variant="outline-info"
className="cardbutton"
size="sm"
onClick={this.editPost.bind(this, post._id, post.message)}
>
Edit
</Button>)}
Complete component
import React, { Component } from "react";
import { Card, Button, Badge, Modal } from "react-bootstrap";
import pic2 from "./pic2.jpg";
import "./Forum.css";
import { BiMessageRounded } from "react-icons/bi";
import axios from "axios";
import moment from "moment";
import { RiDeleteBin6Line } from "react-icons/ri";
import { Link } from "react-router-dom";
//import '../NotificationBar/SideNotification.css';
class Forum extends Component {
constructor(props) {
super(props);
this.state = {
message: "",
posts: [],
showModel: false,
showConfirm: false,
showDeleteConfirm: false,
deletePost: "",
editPost: { message: "", id: "" },
visiblequestions: 10,
visibletype: "",
faculty:"",
timenow:moment().format('H')
};
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
this.loadmore = this.loadmore.bind(this);
this.handletypechange = this.handletypechange.bind(this);
this.handlefaculty = this.handlefaculty.bind(this);
}
handleChange(event) {
this.setState({ message: event.target.value });
}
handleClick(event) {
console.log(this.state.message);
event.preventDefault();
const message = { message: this.state.message ,faculty:this.state.faculty,privacytype:this.state.visibletype};
axios.post("http://localhost:4000/Forum", message).then((res) => {
console.log(res);
console.log(res.data);
this.handleCloseModal();
this.getAllPosts();
});
this.setState({
message: "",
});
}
componentDidMount() {
this.getAllPosts();
this.timelimit();
}
getAllPosts = () => {
axios
.get("http://localhost:4000/Forum/home")
.then((res) => this.setState({ posts: res.data.reverse() }));
};
deletePost = (id) => {
axios
.delete("http://localhost:4000/Forum/" + this.state.deletePost)
.then((res) => {
console.log(res);
this.handleDeleteCloseModal();
this.getAllPosts();
});
};
editPost = (id, message) => {
this.setState((currentState) => ({
...currentState,
showModel: true,
editPost: { message: message, id: id },
}));
console.log(this.state);
};
updatePost = () => {
axios
.patch("http://localhost:4000/Forum/" + this.state.editPost.id, {
message: this.state.editPost.message,
})
.then((res) => {
this.setState((currentState) => ({
...currentState,
showModel: false,
}));
this.getAllPosts();
});
};
onChangehandler = (e) => {
e.persist();
this.setState((currentState) => ({
...currentState,
editPost: { ...currentState.editPost, message: e.target.value },
}));
};
cancleEdit = () => {
this.setState((currentState) => ({ ...currentState, showModel: false }));
this.getAllPosts();
};
handleModal = () => {
this.setState({ showConfirm: true });
};
handleCloseModal = () => {
this.setState({ showConfirm: false });
};
handleDeleteModal = (id) => {
this.setState(() => ({ showDeleteConfirm: true, deletePost: id }));
};
handleDeleteCloseModal = () => {
this.setState({ showDeleteConfirm: false });
};
loadmore() {
this.setState((old) => {
return { visiblequestions: old.visiblequestions + 5 };
});
}
handletypechange(event) {
this.setState(
{ visibletype: event.target.value },
console.log(this.state.visibletype)
);
}
handlefaculty(event) {
this.setState(
{ faculty: event.target.value },
console.log(this.state.faculty)
);
}
timelimit(id){
if(this.state.timenow<2.30){
console.log("yes");
}else{
console.log("no");
}
console.log(this.state.timenow);
}
render() {
return (
<div>
<div class="sidenav">
<h5 style={{ textAlign: "center", color: "white" }}>
Notification Bar
</h5>
</div>
<div className="divstyle">
<Card className="forumstyle">
<Card.Header as="h5">Post Question Here</Card.Header>
<Card.Body>
<Card.Title></Card.Title>
<Card.Text>
<textarea
style={{ width: "460px" }}
placeholder="Please write question here..."
value={this.state.message}
onChange={this.handleChange}
/>
</Card.Text>
</Card.Body>
<div>
<select
className="form-select-sm select"
aria-label="Default select example"
onChange={this.handletypechange}
>
<option defaultValue hidden>Select Type</option>
<option value="all">All</option>
<option value="academic">Academic</option>
<option value="student">Student</option>
</select>
{this.state.visibletype === "student" && (
<select
className="form-select-sm select"
aria-label="Default select example"
onChange={this.handlefaculty}
>
<option defaultValue hidden>Select Faculty</option>
<option value="All">All</option>
<option value="Engineering">Engineering</option>
<option value="Information Technology">
Information Technology
</option>
<option value="Architecture">Architecture</option>
<option value="Business">Business</option>
</select>
)}
</div>
</Card>
<Button
className="button"
variant="primary"
onClick={this.handleModal}
>
Post
</Button>
</div>
<div style={{ backgroundColor: "rgba(192,192,192,0.3)" }}>
{this.state.posts
.slice(0, this.state.visiblequestions)
.map((post) => (
<Card
key={post._id}
style={{
width: "500px",
marginLeft: "30%",
marginBottom: "30px",
marginTop: "20px",
border: "1px solid grey",
}}
>
<Card.Header>
<img
src={pic2}
style={{ width: "20px" }}
className="rounded mr-2"
alt=""
/>
Anushka Praveen
<small style={{ float: "right" }}>
{moment(post.createdAt).fromNow()}
</small>
</Card.Header>
<Card.Body>
<Card.Text>{post.message}</Card.Text>
<Link
to={{
pathname: "Forum/ForumReply",
query: { id: post._id },
}}
>
<Button
variant="outline-info"
className="cardbutton"
size="sm"
>
<BiMessageRounded style={{ marginRight: "2px" }} />
Reply
<Badge className="badgestyle" variant="info">
{post.reply.length}
</Badge>
</Button>
</Link>
{moment(post.createdAt).add(6,'hour').format('H')>this.state.timenow &&(
<Button
variant="outline-info"
className="cardbutton"
size="sm"
onClick={this.editPost.bind(this, post._id, post.message)}
>
Edit
</Button>)}
<Button
variant="outline-danger"
className="carddeletebutton"
size="sm"
onClick={() =>
this.handleDeleteModal(post._id)
} /* {this.deletePost.bind(this, post._id)} */
>
<RiDeleteBin6Line />
</Button>
</Card.Body>
</Card>
))}
<div class="col-md-12 p-3 text-center">
{this.state.visiblequestions < this.state.posts.length && (
<button
type="button"
class="btn btn-outline-info"
onClick={this.loadmore}
>
Read more
</button>
)}
</div>
</div>
<Modal show={this.state.showModel}>
<Modal.Header>
<Modal.Title>Edit Question</Modal.Title>
</Modal.Header>
<Modal.Body>
<textarea
style={{ width: "29rem" }}
value={this.state.editPost.message}
onChange={this.onChangehandler}
>
{this.state.editPost.message}
</textarea>
</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={this.cancleEdit}>
Close
</Button>
<Button variant="primary" onClick={this.updatePost}>
Save
</Button>
</Modal.Footer>
</Modal>
<Modal show={this.state.showConfirm}>
<Modal.Header>
<Modal.Title>Post Question</Modal.Title>
</Modal.Header>
<Modal.Body>Do you want post this Question?</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={this.handleCloseModal}>
Close
</Button>
<Button variant="danger" onClick={this.handleClick}>
Post Question
</Button>
</Modal.Footer>
</Modal>
<Modal show={this.state.showDeleteConfirm}>
<Modal.Header>
<Modal.Title>Delete Question</Modal.Title>
</Modal.Header>
<Modal.Body>Do you want Delete this Question?</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={this.handleDeleteCloseModal}>
Close
</Button>
<Button variant="danger" onClick={this.deletePost}>
Delete Question
</Button>
</Modal.Footer>
</Modal>
</div>
);
}
}
export default Forum;
Maybe trying to conditionally render it this way will help.
{(!(moment(post.createdAt).add(6,'hour').format('H')< this.state.timenow))?
<Button
variant="outline-info"
className="cardbutton"
size="sm"
onClick={this.editPost.bind(this, post._id, post.message)}
>
Edit
</Button>:<>"empty"</>}
Your conditional rendering seems fine. || operator evaluates the left-hand side and if it is false, it moves to the right hand side. Whereas && operator evaluates the left-hand side and continues if it is true
You want to show the button, if it is less than 6 hours. So you want (moment(post.createdAt).add(6,'hour').format('H') < this.state.timenow) evaluate to true and render the Button only if the statement is true
{(moment(post.createdAt).add(6,'hour').format('H') < this.state.timenow) && (
<Button
variant="outline-info"
className="cardbutton"
size="sm"
onClick={this.editPost.bind(this, post._id, post.message)}
>
Edit
</Button>)}
I have just started updating some class components into functional components but now when navigating through to other pages (using ) the page will only display after an initial refresh.
Below is an example
This is a component I have updated to use the useState() hook.
function AdminWorkstationss({ initialCount }) {
const [WSAHeaders, setWSAHeaders] = useState([{}]);
const [currentPage, setPage] = useState(1);
const [WSAPerPage, setWSA] = useState(10);
const [pageNumbers, createPageNumber] = useState([]);
const [loadingToken, setLoadingToken] = useState(null);
const indexOfLastTodo = currentPage * WSAPerPage;
const indexOfFirstTodo = indexOfLastTodo - WSAPerPage;
const currentTodos = WSAHeaders.slice(indexOfFirstTodo, indexOfLastTodo);
// const pageNumbers = [];
useEffect(async () => {
setLoadingToken(true);
let recordset = await fetch(`/admin-completed-workstations`);
let results = await recordset.json();
setWSAHeaders(results.recordset);
var pNumbers = [];
for (
let i = 1;
i <= Math.ceil(results.recordset.length / WSAPerPage);
i++
) {
// pageNumbers.push(i);
pNumbers.push(i);
}
createPageNumber(pNumbers);
setLoadingToken(false);
}, []);
function handleClick(event) {
setPage(Number(event.target.id));
}
if (!loadingToken) {
return (
<>
<Fade>
<Slide left>
<h2 style={{ textAlign: "center" }}>
Workstation Assessments(<b> Completed</b>)
</h2>
</Slide>
</Fade>
<ul>
<button disabled className="btn btn-secondary">
Workstation Assessments
</button>
<Link to="./admin-center">
<button className="btn btn-secondary">Edit Questions</button>
</Link>
<Link to="./admin-center-view-users">
<button className="btn btn-secondary">View Users</button>
</Link>
<DropdownButton
style={{ float: "right" }}
id="dropdown-basic-button"
title="WSA's Per Page"
>
<Dropdown.Item onClick={() => setWSA(10)}>10</Dropdown.Item>
<Dropdown.Item onClick={() => setWSA(20)}>20</Dropdown.Item>
<Dropdown.Item onClick={() => setWSA(40)}>40</Dropdown.Item>
<Dropdown.Item onClick={() => setWSA(100)}>100</Dropdown.Item>
</DropdownButton>{" "}
<DropdownButton
style={{ float: "right" }}
id="dropdown-basic-button"
title="Completed"
>
//HERE. This button in drop down takes me to the correct page but just requires a refresh or it will not load.
<Dropdown.Item>
{" "}
<Link to="admin-view-workstation-assessments-declined">
In Progress
</Link>
</Dropdown.Item>
</DropdownButton>{" "}
</ul>
{currentTodos.map(number => (
<ul>
{" "}
<div className="jumbotron">
//Mapping child component
<Questions
workStation={number.AssignedWorkstation}
date={number.Date}
completeToken={number.QuestionStatus}
RUId={number.RUId}
WSAId={number.WSAId}
></Questions>
</div>
</ul>
))}
<div style={{ alignContent: "center", width: "10%" }}></div>
<div style={{ textAlign: "center", alignContent: "center" }}>
{" "}
<b> Current Page </b>: {currentPage}
<br />
<div>
{pageNumbers.map(number => (
<button
className="btn btn-primary"
key={number}
id={number}
onClick={handleClick}
>
{number}
</button>
))}
</div>
</div>
<br />
</>
);
} else if (loadingToken) {
return (
<>
<ul>
<button disabled className="btn btn-secondary">
Workstation Assessments
</button>
<Link to="./admin-center">
<button className="btn btn-secondary">Edit Questions</button>
</Link>
<Link to="./admin-center-view-users">
<button className="btn btn-secondary">View Users</button>
</Link>
<DropdownButton
style={{ float: "right" }}
id="dropdown-basic-button"
title="Completed"
>
<Dropdown.Item>
{" "}
<Link to="admin-view-workstation-assessments-declined">
In Progress
</Link>
</Dropdown.Item>
</DropdownButton>{" "}
</ul>
<h3 style={{ textAlign: "center" }}>LOADING</h3>
</>
);
}
}
I then have a child component of this one (this is within the .map) called questions. This is still a class component will this be the issue?
class Questions extends React.Component {
constructor(props) {
super(props);
console.log(props);
this.state = {
...props,
questionsAccepted: [],
questionsAcceptedCounter: "",
selectedSet: [],
ViewActivityToken: false,
noteToBeAdded: "",
notesFromDB: [],
addNoteToken: false,
answeredQuestions: []
};
}
render() {
if (!this.state.ViewActivity) {
if (!this.state.viewDetails && !this.state.ViewActivityToken) {
console.log(moment.locale());
return (
<div>
<ModalCompletedQuestions
RUId={this.props.RUId}
workStation={this.props.workStation}
WSAId={this.props.WSAId}
/>
// This Link is a link to another page but this page also needs a refresh before it is visible.
<Link
to={{
pathname: "/admin-view-full-user-wsa-responses",
state: {
WSAId: this.props.WSAId
}
}}
>
<button style={{ float: "right" }} className="btn btn-primary">
View Full Details
</button>
</Link>
<br />
<li>
<b>User Id: </b>
{this.props.RUId}
</li>
<li>
<b>Workstation: </b>
{this.props.workStation}
</li>
<li>
<b>Date: </b>
{moment(this.props.date).format("L")}
</li>
<li>
<b>Complete Token: </b>
{this.props.completeToken}
</li>
</div>
);
} else if (this.state.viewDetails && !this.state.ViewActivityToken) {
return (
<div>
<button
style={{ float: "right" }}
onClick={e =>
this.setState({
ViewActivity: false,
viewDetails: false,
ViewActivityToken: false,
addNoteToken: false
})
}
className="btn btn-secondary"
>
Revert
</button>
<br />
<br />
{this.state.selectedSet &&
this.state.selectedSet.map((item, index) => {
return (
<div>
<li>
{" "}
<b>{item.QuestionWhenAnswered}</b>{" "}
</li>
<li>{item.QuestionResponse}</li>
<li>{item.Accepted}</li>
</div>
);
})}
</div>
);
}
} else if (this.state.ViewActivity && !this.state.addNoteToken) {
return (
<>
<button
style={{ float: "right" }}
onClick={e =>
this.setState({
ViewActivity: false,
viewDetails: false,
ViewActivityToken: false,
addNoteToken: false
})
}
className="btn btn-secondary"
>
Revert
</button>
<br />
<li>
<b>User Id: </b>
{this.props.RUId}
</li>
<li>
<b>Workstation: </b>
{this.props.workStation}
</li>
<li>
<b>Date: </b>
{moment(this.props.date).format("DD/MM/YYYY")}
</li>
<li>
<b>Complete Token: </b>
{this.props.completeToken}
</li>
{this.state.notesFromDB &&
this.state.notesFromDB.map((item, index) => {
return (
<div
style={{
backgroundColor: "white",
border: "inset",
borderWidth: "0.2px"
}}
>
<div style={{ float: "right" }}>
{moment(item.CreationTime).format("HH:MM DD/MM/YYYY ")}
</div>
<div>
<b>{`${item.UserStatus} `}</b>
</div>
<div style={{ textAlign: "left" }}>{item.Notes}</div>
</div>
);
})}
<br />
<button
onClick={this.AddNoteBtn}
className="btn btn-primary"
style={{ width: "100%" }}
>
Add Note
</button>
</>
);
}
}
}
Why are these pages not loading automatically and why would they need a refresh to laod? Is there any chance it is because I am using class components along with functional components? Any help is much appreciated.
This was due to me making useEffect async when this was changed so that the use effect was not using async everything worked fine again.
I am working on a react project with similar functionality to a social media site. I have a user profile component below that has links to other user profiles(towards bottom of code below) that are being followed by the current user. Essentially what I am trying to do is re-render the same component with a different user. However, the link to the new user profile doesn't result in the getProfile action getting called so the redux state doesn't update. How can I navigate to the new profile and have the useEffect hook get called again with the new username?
Thank You!
import React, { useEffect, useState } from "react";
import PropTypes from "prop-types";
import { connect } from "react-redux";
import { Link } from "react-router-dom";
import GalleryItem from "../gallery-item/gallery-item.component";
import {
getProfile,
addFollow,
removeFollow
} from "../../redux/profile/profile.actions";
import { FontAwesomeIcon } from "#fortawesome/react-fontawesome";
import { faSpinner, faUserEdit } from "#fortawesome/free-solid-svg-icons";
const Profile = ({
getProfile,
addFollow,
removeFollow,
auth,
profile: { userProfile, loading },
props
}) => {
const userAlias = props.match.params.alias;
useEffect(() => {
getProfile(userAlias);
}, [getProfile]);
return loading ? (
<div class="d-flex justify-content-center">
<FontAwesomeIcon
icon={faSpinner}
className="fa-spin"
style={{ height: "50px", width: "50px", color: "white" }}
/>
</div>
) : (
<div className="container ">
<div className="row">
<div className="col-md-12 align-self-center">
<img
className="rounded-circle float-left shadow-lg"
alt="100x100"
src={userProfile.userProfileImage}
data-holder-rendered="true"
style={{ height: "200px", width: "200px" }}
/>
<div
className="vertical-center"
style={{ marginLeft: "260px", marginTop: "50px" }}
>
<h2>
{auth.user === null || auth.user.alias !== userAlias ? (
<b style={{ color: "white" }}>{userAlias}</b>
) : auth.user.alias === userAlias ? (
<b style={{ color: "white" }}>
{userAlias}
<Link className="" to="/profile/edit">
<FontAwesomeIcon
icon={faUserEdit}
className="fontAwesome"
style={{ paddingLeft: "10px", color: "limegreen" }}
/>
</Link>
</b>
) : (
<b>{userAlias}</b>
)}
</h2>
<p>
<b style={{ color: "white" }}>
{" "}
{userProfile.posts.length} Posts
</b>
<b style={{ color: "white" }}>
{" "}
{userProfile.followers.length} Followers{" "}
</b>
<b style={{ color: "white" }}>
{" "}
{userProfile.following.length} Following{" "}
</b>
</p>
{auth.user === null || auth.user.alias === userAlias ? null : auth
.user.alias !== userAlias &&
userProfile.followers.some(
e => e.userAlias === auth.user.alias
) ? (
<button
type="button"
className="btn btn-primary btn-lg "
onClick={e => removeFollow(userProfile.userId)}
>
Following
</button>
) : auth.user.alias !== userAlias ? (
<button
type="button"
className="btn btn-primary btn-lg "
onClick={e => addFollow(userProfile.userId)}
>
Not Following
</button>
) : (
<button
type="button"
className="btn btn-primary btn-lg "
disabled
>
Follow/Unfollow
</button>
)}
</div>
</div>
</div>
<hr />
<div className="row d-flex justify-content-center">
{userProfile.posts.map((post, i) => (
<GalleryItem key={i} post={post} />
))}
</div>
{userProfile.following.length > 0 ? (
<div>
<h1 className="text-white text-center mt-5">Following</h1>
<hr />
**<div className="row justify-content-center text-center px-auto">
{userProfile.following.map((profile, i) => (
<Link className="" to={`/profile/${profile.userAlias}`}>
<img
className="rounded-circle border border-info m-4"
alt="100x100"
src={profile.getFollowingUserProfileImageUrl}
data-holder-rendered="true"
style={{ height: "80px", width: "80px" }}
/>
<div
className="vertical-center"
style={{ marginBottom: "20px", color: "black" }}
>
<h5>{profile.userAlias}</h5>
</div>
</Link>
))}
</div>**
</div>
) :(<div></div>)}
</div>
);
};
Profile.propTypes = {
getProfile: PropTypes.func.isRequired,
profile: PropTypes.object.isRequired,
auth: PropTypes.object.isRequired,
props: PropTypes.object.isRequired
};
const mapStateToProps = (state, ownProps) => ({
auth: state.auth,
profile: state.profile,
props: ownProps
});
export default connect(
mapStateToProps,
{ getProfile, addFollow, removeFollow }
)(Profile);
You need to track userAlias in the useEffect's dependencies list, the api callback will be called each time it changes.
const userAlias = props.match.params.alias;
useEffect(() => {
getProfile(userAlias);
}, [getProfile, userAlias]);
I am doing reactjs and redux for developing dashboard. I have done add, delete but editing is not working. When user clicks on item, the textfield should display with its current value and able to submit the changes. I can show textfield when clicked but could not show the current value of that item which is clicked. To display textField i have to use onClick on the li tag otherwise i could pass data like using this.props.editTab(tab). How can i now send data of clicked item to editTab action ?
constructor(props) {
super(props);
this.state = { open: false, editing: false };
}
editTab() {
const tabs = _.map(this.props.tabs, (tab) => {
if (tab.editable) {
return (
<li
className="list-group-items delete-tab-list"
onClick={() => this.setState({ editing: true })}
key={tab.id}
>
<i className="material-icons">{tab.icon}</i>{tab.name}
</li>
);
}
});
return (
<div className="device-action">
<Dialog
title="Update a Tab"
modal={false}
bodyStyle={{ background: '#fff' }}
contentStyle={customContentStyle}
actionsContainerStyle={{ background: '#fff' }}
titleStyle={{ background: '#fff', color: '#1ab394' }}
open={this.props.createTab.open}
onRequestClose={this.props.closeTabIcon}
>
<ul className="list-group">
{ this.state.editing ?
<EditForm
tab={this.props.tabs}
editing={this.state.editing}
/> :
tabs
}
</ul>
</Dialog>
</div>
);
}
handleEditSave = (name, icon) => {
this.props.editTab(name, icon);
}
render() {
return (
<div>
<form onSubmit={this.handleEditSave}>
<div className="tab-name">
<TextField
floatingLabelText="Name"
onChange={(name) => { this.setState({ name: name.target.value }); }}
/>
</div>
<div className="icon">
<AutoComplete
floatingLabelText="select any icon"
filter={AutoComplete.noFilter}
openOnFocus
onNewRequest={(e) => { this.setState({ icon: e.id }); }}
/>
</div>
<button className="btn">Save</button>
</form>
</div>
);
}
How can i pass clicked item data to EditForm component so i can trigger my action in this.props.editTab(tab) this way ?
You can simply track the tab you editing by saving it on the state.
This will work only if you want to edit 1 tab at time. otherwise you can use Object/Array.
constructor(props) {
super(props);
this.state = { open: false, editing: null };
}
editTab() {
const tabs = _.map(this.props.tabs, (tab) => {
if (tab.editable) {
return (
<li
className="list-group-items delete-tab-list"
onClick={() => this.setState({ editing: tab })}
key={tab.id}
>
<i className="material-icons">{tab.icon}</i>{tab.name}
</li>
);
}
});
const { editing } = this.state;
// editing is the Tab object that we edit
if (editing)
console.log("Editing tab: " + editable.name);
return (
<div className="device-action">
<Dialog
title="Update a Tab"
modal={false}
bodyStyle={{ background: '#fff' }}
contentStyle={customContentStyle}
actionsContainerStyle={{ background: '#fff' }}
titleStyle={{ background: '#fff', color: '#1ab394' }}
open={this.props.createTab.open}
onRequestClose={this.props.closeTabIcon}
>
<ul className="list-group">
{ this.state.editing ?
<EditForm
tab={this.props.tabs}
editing={this.state.editing}
/> :
tabs
}
</ul>
</Dialog>
</div>
);
}
handleEditSave = (name, icon) => {
this.props.editTab(name, icon);
}
render() {
return (
<div>
<form onSubmit={this.handleEditSave}>
<div className="tab-name">
<TextField
floatingLabelText="Name"
onChange={(name) => { this.setState({ name: name.target.value }); }}
/>
</div>
<div className="icon">
<AutoComplete
floatingLabelText="select any icon"
filter={AutoComplete.noFilter}
openOnFocus
onNewRequest={(e) => { this.setState({ icon: e.id }); }}
/>
</div>
<button className="btn">Save</button>
</form>
</div>
);
}