Force refresh of states instead of modifying objects

This commit is contained in:
Tanner Collin 2020-01-18 01:27:56 +00:00
parent 6c8f6f7baa
commit cb8ac3cf63
5 changed files with 44 additions and 44 deletions

View File

@ -6,6 +6,7 @@ import { BasicTable, staticUrl, requester } from './utils.js';
import { LoginForm, SignupForm } from './LoginSignup.js'; import { LoginForm, SignupForm } from './LoginSignup.js';
function ChangePasswordForm(props) { function ChangePasswordForm(props) {
const { token } = props;
const [input, setInput] = useState({}); const [input, setInput] = useState({});
const [error, setError] = useState({}); const [error, setError] = useState({});
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@ -17,7 +18,7 @@ function ChangePasswordForm(props) {
const handleSubmit = (e) => { const handleSubmit = (e) => {
setLoading(true); setLoading(true);
requester('/password/change/', 'POST', props.token, input) requester('/password/change/', 'POST', token, input)
.then(res => { .then(res => {
setError({}); setError({});
history.push('/'); history.push('/');
@ -67,7 +68,8 @@ function ChangePasswordForm(props) {
}; };
export function AccountForm(props) { export function AccountForm(props) {
const member = props.user.member; const { token, user, refreshUser } = props;
const member = user.member;
const [input, setInput] = useState({ ...member, set_details: true }); const [input, setInput] = useState({ ...member, set_details: true });
const [error, setError] = useState({}); const [error, setError] = useState({});
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@ -80,10 +82,10 @@ export function AccountForm(props) {
const handleSubmit = (e) => { const handleSubmit = (e) => {
setLoading(true); setLoading(true);
requester('/members/' + member.id + '/', 'PATCH', props.token, input) requester('/members/' + member.id + '/', 'PATCH', token, input)
.then(res => { .then(res => {
setError({}); setError({});
props.setUserCache({...props.user, member: res}); refreshUser();
history.push('/'); history.push('/');
}) })
.catch(err => { .catch(err => {

View File

@ -5,11 +5,12 @@ import { Container, Checkbox, Divider, Dropdown, Form, Grid, Header, Icon, Image
import { BasicTable, staticUrl, requester } from './utils.js'; import { BasicTable, staticUrl, requester } from './utils.js';
function AdminCardDetail(props) { function AdminCardDetail(props) {
const [input, setInput] = useState({ ...props.card }); const { token, result, card } = props;
const [input, setInput] = useState({ ...card });
const [error, setError] = useState(false); const [error, setError] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(false); const [success, setSuccess] = useState(false);
const id = props.card.id; const id = card.id;
const handleValues = (e, v) => setInput({ ...input, [v.name]: v.value }); const handleValues = (e, v) => setInput({ ...input, [v.name]: v.value });
const handleUpload = (e, v) => setInput({ ...input, [v.name]: e.target.files[0] }); const handleUpload = (e, v) => setInput({ ...input, [v.name]: e.target.files[0] });
@ -19,8 +20,8 @@ function AdminCardDetail(props) {
const handleSubmit = (e) => { const handleSubmit = (e) => {
setLoading(true); setLoading(true);
setSuccess(false); setSuccess(false);
const data = { ...input, member_id: props.result.member.id }; const data = { ...input, member_id: result.member.id };
requester('/cards/'+id+'/', 'PUT', props.token, data) requester('/cards/'+id+'/', 'PUT', token, data)
.then(res => { .then(res => {
setLoading(false); setLoading(false);
setSuccess(true); setSuccess(true);
@ -37,7 +38,7 @@ function AdminCardDetail(props) {
const handleDelete = (e) => { const handleDelete = (e) => {
e.preventDefault(); e.preventDefault();
requester('/cards/'+id+'/', 'DELETE', props.token) requester('/cards/'+id+'/', 'DELETE', token)
.then(res => { .then(res => {
setInput(false); setInput(false);
}) })
@ -98,13 +99,14 @@ function AdminCardDetail(props) {
</Segment> </Segment>
: :
<Segment raised color='black'> <Segment raised color='black'>
Deleted card: {props.card.card_number} Deleted card: {card.card_number}
</Segment> </Segment>
); );
}; };
export function AdminMemberCards(props) { export function AdminMemberCards(props) {
const cards = props.result.cards; const { token, result, refreshResult } = props;
const cards = result.cards;
const [input, setInput] = useState({ active_status: 'card_active' }); const [input, setInput] = useState({ active_status: 'card_active' });
const [error, setError] = useState(false); const [error, setError] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
@ -119,13 +121,13 @@ export function AdminMemberCards(props) {
const handleSubmit = (e) => { const handleSubmit = (e) => {
setLoading(true); setLoading(true);
setSuccess(false); setSuccess(false);
const data = { ...input, member_id: props.result.member.id }; const data = { ...input, member_id: result.member.id };
requester('/cards/', 'POST', props.token, data) requester('/cards/', 'POST', token, data)
.then(res => { .then(res => {
setLoading(false); setLoading(false);
setSuccess(true); setSuccess(true);
setError(false); setError(false);
props.setResult({ ...props.result, cards: [...cards, res] }); refreshResult();
}) })
.catch(err => { .catch(err => {
setLoading(false); setLoading(false);
@ -194,7 +196,8 @@ export function AdminMemberCards(props) {
}; };
export function AdminMemberForm(props) { export function AdminMemberForm(props) {
const [input, setInput] = useState(props.result.member); const { token, result, refreshResult } = props;
const [input, setInput] = useState(result.member);
const [error, setError] = useState(false); const [error, setError] = useState(false);
const [loading, setLoading] = useState(false); const [loading, setLoading] = useState(false);
const [success, setSuccess] = useState(false); const [success, setSuccess] = useState(false);
@ -208,12 +211,12 @@ export function AdminMemberForm(props) {
const handleSubmit = (e) => { const handleSubmit = (e) => {
setLoading(true); setLoading(true);
setSuccess(false); setSuccess(false);
requester('/members/' + id + '/', 'PATCH', props.token, input) requester('/members/' + id + '/', 'PATCH', token, input)
.then(res => { .then(res => {
setLoading(false); setLoading(false);
setSuccess(true); setSuccess(true);
setError(false); setError(false);
props.setResult({ ...props.result, member: res }); refreshResult();
}) })
.catch(err => { .catch(err => {
setLoading(false); setLoading(false);

View File

@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect, useReducer } from 'react';
import { BrowserRouter as Router, Switch, Route, Link, useParams } from 'react-router-dom'; import { BrowserRouter as Router, Switch, Route, Link, useParams } from 'react-router-dom';
import './light.css'; import { Container, Divider, Dropdown, Form, Grid, Header, Icon, Image, Menu, Message, Segment, Table } from 'semantic-ui-react'; import './light.css'; import { Container, Divider, Dropdown, Form, Grid, Header, Icon, Image, Menu, Message, Segment, Table } from 'semantic-ui-react';
import { requester } from './utils.js'; import { requester } from './utils.js';
@ -16,6 +16,7 @@ import { Footer } from './Footer.js';
function App() { function App() {
const [token, setToken] = useState(localStorage.getItem('token', '')); const [token, setToken] = useState(localStorage.getItem('token', ''));
const [user, setUser] = useState(JSON.parse(localStorage.getItem('user', 'false'))); const [user, setUser] = useState(JSON.parse(localStorage.getItem('user', 'false')));
const [refreshCount, refreshUser] = useReducer(x => x + 1, 0);
function setTokenCache(x) { function setTokenCache(x) {
setToken(x); setToken(x);
@ -36,7 +37,7 @@ function App() {
console.log(err); console.log(err);
setUser(false); setUser(false);
}); });
}, [token]); }, [token, refreshCount]);
function logout() { function logout() {
setTokenCache(''); setTokenCache('');
@ -121,14 +122,14 @@ function App() {
</Menu> </Menu>
<Route exact path='/'> <Route exact path='/'>
<Home token={token} setTokenCache={setTokenCache} user={user} setUserCache={setUserCache} /> <Home token={token} setTokenCache={setTokenCache} user={user} refreshUser={refreshUser} />
</Route> </Route>
<div className='topPadding'> <div className='topPadding'>
{user && user.member.set_details ? {user && user.member.set_details ?
<Switch> <Switch>
<Route path='/account'> <Route path='/account'>
<Account token={token} user={user} setUserCache={setUserCache} /> <Account token={token} user={user} refreshUser={refreshUser} />
</Route> </Route>
<Route path='/transactions/:id'> <Route path='/transactions/:id'>
@ -154,7 +155,7 @@ function App() {
</Route> </Route>
<Route path='/classes/:id'> <Route path='/classes/:id'>
<ClassDetail token={token} user={user} setUserCache={setUserCache} /> <ClassDetail token={token} user={user} refreshUser={refreshUser} />
</Route> </Route>
<Route path='/classes'> <Route path='/classes'>
<Classes token={token} /> <Classes token={token} />

View File

@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect, useReducer } from 'react';
import { BrowserRouter as Router, Switch, Route, Link, useParams } from 'react-router-dom'; import { BrowserRouter as Router, Switch, Route, Link, useParams } from 'react-router-dom';
import './light.css'; import './light.css';
import { Button, Container, Divider, Dropdown, Form, Grid, Header, Icon, Image, Menu, Message, Segment, Table } from 'semantic-ui-react'; import { Button, Container, Divider, Dropdown, Form, Grid, Header, Icon, Image, Menu, Message, Segment, Table } from 'semantic-ui-react';
@ -66,7 +66,8 @@ export function Classes(props) {
return ( return (
<Container> <Container>
<Header size='large'>Class List</Header> <Header size='large'>Class List</Header>
<Header size='medium'>Upcoming</Header>
<Header size='medium'>Upcoming</Header>
{classes ? {classes ?
<ClassTable classes={classes.filter(x => x.datetime > now)} /> <ClassTable classes={classes.filter(x => x.datetime > now)} />
: :
@ -85,8 +86,9 @@ export function Classes(props) {
export function ClassDetail(props) { export function ClassDetail(props) {
const [clazz, setClass] = useState(false); const [clazz, setClass] = useState(false);
const [refreshCount, refreshClass] = useReducer(x => x + 1, 0);
const [error, setError] = useState(false); const [error, setError] = useState(false);
const { token, user, setUserCache } = props; const { token, user, refreshUser } = props;
const { id } = useParams(); const { id } = useParams();
const userTraining = user.training.find(x => x.session.id == id); const userTraining = user.training.find(x => x.session.id == id);
@ -99,20 +101,17 @@ export function ClassDetail(props) {
console.log(err); console.log(err);
setError(true); setError(true);
}); });
}, []); }, [refreshCount]);
const handleSignup = () => { const handleSignup = () => {
const data = { attendance_status: 'waiting for payment', session: id }; const data = { attendance_status: 'waiting for payment', session: id };
requester('/training/', 'POST', token, data) requester('/training/', 'POST', token, data)
.then(res => { .then(res => {
// bad code: refreshClass();
const newClass = { ...clazz, student_count: clazz.student_count+1 }; refreshUser();
setUserCache({ ...user, training: [...user.training, {...res, session: newClass }] });
setClass(newClass);
}) })
.catch(err => { .catch(err => {
console.log(err); console.log(err);
setError(true);
}); });
}; };
@ -120,14 +119,8 @@ export function ClassDetail(props) {
const data = { attendance_status: newStatus, session: id }; const data = { attendance_status: newStatus, session: id };
requester('/training/'+userTraining.id+'/', 'PUT', token, data) requester('/training/'+userTraining.id+'/', 'PUT', token, data)
.then(res => { .then(res => {
// bad code: refreshClass();
const studentChange = newStatus === 'withdrawn' ? -1 : 1 refreshUser();
const newClass = { ...clazz, student_count: clazz.student_count + studentChange };
const trainingIndex = user.training.indexOf(userTraining);
const newTraining = user.training;
newTraining[trainingIndex] = {...res, session: newClass };
setUserCache({ ...user, training: newTraining });
setClass(newClass);
}) })
.catch(err => { .catch(err => {
console.log(err); console.log(err);

View File

@ -1,4 +1,4 @@
import React, { useState, useEffect } from 'react'; import React, { useState, useEffect, useReducer } from 'react';
import { BrowserRouter as Router, Switch, Route, Link, useParams } from 'react-router-dom'; import { BrowserRouter as Router, Switch, Route, Link, useParams } from 'react-router-dom';
import './light.css'; import './light.css';
import { Button, Container, Divider, Dropdown, Form, Grid, Header, Icon, Image, Input, Item, Menu, Message, Segment, Table } from 'semantic-ui-react'; import { Button, Container, Divider, Dropdown, Form, Grid, Header, Icon, Image, Input, Item, Menu, Message, Segment, Table } from 'semantic-ui-react';
@ -74,6 +74,7 @@ export function Members(props) {
export function MemberDetail(props) { export function MemberDetail(props) {
const [result, setResult] = useState(false); const [result, setResult] = useState(false);
const [refreshCount, refreshResult] = useReducer(x => x + 1, 0);
const [error, setError] = useState(false); const [error, setError] = useState(false);
const { token, user } = props; const { token, user } = props;
const { id } = useParams(); const { id } = useParams();
@ -87,7 +88,7 @@ export function MemberDetail(props) {
console.log(err); console.log(err);
setError(true); setError(true);
}); });
}, []); }, [refreshCount]);
const member = result.member || false; const member = result.member || false;
@ -105,7 +106,7 @@ export function MemberDetail(props) {
</p> </p>
{isAdmin(user) ? {isAdmin(user) ?
<AdminMemberInfo result={result} setResult={setResult} {...props} /> <AdminMemberInfo result={result} refreshResult={refreshResult} {...props} />
: :
<BasicTable> <BasicTable>
<Table.Body> <Table.Body>
@ -124,13 +125,13 @@ export function MemberDetail(props) {
<Grid.Column> <Grid.Column>
{isAdmin(user) && <Segment padded> {isAdmin(user) && <Segment padded>
<AdminMemberForm result={result} setResult={setResult} {...props} /> <AdminMemberForm result={result} refreshResult={refreshResult} {...props} />
</Segment>} </Segment>}
</Grid.Column> </Grid.Column>
</Grid> </Grid>
{isAdmin(user) && <Segment padded> {isAdmin(user) && <Segment padded>
<AdminMemberCards result={result} setResult={setResult} {...props} /> <AdminMemberCards result={result} refreshResult={refreshResult} {...props} />
</Segment>} </Segment>}
</div> </div>