this.setState not updating state - reactjs

For some reason my this.state call is not updating the state in my roleClicked function. I can't seem to figure out what the problem is. Here is the code:
import React, { Component } from 'react'
import { Redirect } from 'react-router-dom';
import instance from '../../../config/axios';
import ls from 'local-storage';
import Sidenav from '../../layout/Sidenav'
import isLoggedIn from '../../../helpers/isLoggedIn';
import redirectToLogin from '../../../helpers/redirectToLogin';
import apiErrorHandler from '../../../helpers/apiErrorHandler';
import RolesHeader from './RolesHeader';
import '../../../App.css'
import { Table, Pagination, Input, Alert } from 'antd';
export default class ViewRoles extends Component {
state = {
loggedIn: true,
roleSelected: false,
roleSelectedId: null,
rolesTable: {
columns: null,
dataSource: null,
currentPageNumber: null,
currentPageSize: null,
total: null,
},
filters: {
roleName: null
},
displays: {
createRoleView: false,
roleCreatedAlert: false,
},
errors: null
}
componentDidMount = () => {
//here i make AJAX calls to set rolesTables
}
roleClicked = (record) => {
console.log("clicked")
this.setState({
roleSelected: true,
roleSelectedId: record.key
})
}
render() {
if(this.state.roleSelected) {
const roleUrl = "/roles/" + this.state.roleSelectedId
return <Redirect to={roleUrl}/>
}
return (
<React.Fragment>
<Sidenav activeLink="roles"/>
<Table
className="border"
columns={this.state.rolesTable.columns}
dataSource={this.state.rolesTable.dataSource}
pagination={false}
onRow={(record) => {
return {
onClick: () => this.roleClicked(record)
}}}
/>
<Pagination
className="m-3"
current={this.state.rolesTable.currentPageNumber}
pageSize={this.state.rolesTable.currentPageSize}
total={this.state.rolesTable.total}
onChange={this.loadRolesTable}
/>
</React.Fragment>)
}
}
The function runs as expected but the state is not updated. Any idea what the problem could be?
Everywhere else I use this.setState it works. The full code can be found on this link.

I updated roleClicked to this and it works. I still have no idea why the initial code didn't work.
viewRole = async (record) => {
var currentState = this.state;
currentState.roleSelected = true;
currentState.roleSelectedId = record.key;
await this.setState(currentState);
console.log(this.state)
}
Just changing it to Async didn't work. Only assigning the state to currentState and then updating currentState and using it in setState worked. And now it works both synchronously and asynchronously.

try something like this
this.setState(function(state, props) {
return {
...state,
roleSelected: true,
roleSelectedId: record.key
};
});

Related

React - Unable to set state from the response on initial render

This is the response from redux store :
{
"newsletter": true,
"orderConfirmation": true,
"shippingInformation": true,
"orderEnquiryConfirmation": true,
}
This is the jsx file, where am trying to set state. The idea is setting the state from the response and add an onChange handle to each checkboxes.
But currently am receiving a correct response but I tried to set state in didUpdate, DidMount but no luck. I want to know the correct place to set state on initial render of the component.
import React from 'react';
import Component from '../../assets/js/app/component.jsx';
import { connect } from 'react-redux';
import * as actionCreators from '../../assets/js/app/some/actions';
import { bindActionCreators } from 'redux';
import Checkbox from '../checkbox/checkbox.jsx';
const mapStateToProps = (state, ownProps) => {
return {
...state.emailSubscriptions
}
}
const mapDispatchToProps = dispatch => {
return {
actions: bindActionCreators(actionCreators, dispatch)
}
}
#connect(mapStateToProps, mapDispatchToProps)
class EmailSubscriptions extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
this.props.actions.getEmailSubscriptions();
this.setState({ // Not setting state
notifications: [
newsletter = this.props.newsletter,
orderConfirmation = this.props.orderConfirmation,
shippingInformation = this.props.shippingInformation,
orderEnquiryConfirmation = this.props.orderEnquiryConfirmation
]
})
}
render() {
return (
<div>
Here I want to use loop through state to create checkboxes
{this.state.notifications&& this.state.notifications.map((item, index) => {
const checkboxProps = {
id: 'subscription' + index,
name: 'subscription',
checked: item.subscription ? true : false,
onChange: (e)=>{ return this.onChange(e, index)},
};
return <div key={index}>
<Checkbox {...checkboxProps} />
</div>
</div>
)
}
}
export default EmailSubscriptions;
I hope getEmailSubscriptions is an async action, so your setState won't update the state as you intended. add componentDidUpdate hook in your class component and your setState statement within an if statement that has an expression checking your props current and prev value.
You can do something like this.
componentDidMount() {
this.props.actions.getEmailSubscriptions();
}
componentDidUpdate(prevProps, prevState, snapshot){
if(this.props.<prop_name> != prevProps.<prop_name>){
this.setState({
notifications: [
newsletter = this.props.newsletter,
orderConfirmation = this.props.orderConfirmation,
shippingInformation = this.props.shippingInformation,
orderEnquiryConfirmation = this.props.orderEnquiryConfirmation
]
})
}
}

How to update prop values in Child class component when Parent class component state is changed? : React Native

I have a parent class component called CardView.js which contains a child class component called Tab.js (which contains a FlatList).
When a button is pressed in CardView.js, a modal appears with various options. A user chooses an option and presses 'OK' on the modal. At this point the onOKHandler method in the parent component updates the parent state (tabOrderBy: orderBy and orderSetByModal: true). NOTE: These two pieces of state are passed to the child component as props.
Here is what I need:
When the onOKHandler is pressed in the parent, I need the child component to re-render with it's props values reflecting the new state values in the parent state. NOTE: I do not want the Parent Component to re-render as well.
At the moment when onOKHandler is pressed, the child component reloads, but it's props are still showing the OLD state from the parent.
Here is what I have tried:
When the onOKHandler is pressed, I use setState to update the parent state and then I use the setState callback to call a method in the child to reload the child. The child reloads but its props are not updated.
I have tried using componentDidUpdate in the child which checks when the prop orderSetByModal is changed. This does not work at all.
I have tried many of the recommendations in other posts like this - nothing works! Where am I going wrong please? Code is below:
Parent Component: CardView.js
import React from "react";
import { View } from "react-native";
import { Windows} from "../stores";
import { TabView, SceneMap } from "react-native-tab-view";
import { Tab, TabBar, Sortby } from "../components";
class CardView extends React.Component {
state = {
level: 0,
tabIndex: 0,
tabRoutes: [],
recordId: null,
renderScene: () => {},
showSortby: false,
orderSetByModal: false,
tabOrderBy: ''
};
tabRefs = {};
componentDidMount = () => {
this.reload(this.props.windowId, null, this.state.level, this.state.tabIndex);
};
reload = (windowId, recordId, level, tabIndex) => {
this.setState({ recordId, level, tabIndex });
const tabRoutes = Windows.getTabRoutes(windowId, level);
this.setState({ tabRoutes });
const sceneMap = {};
this.setState({ renderScene: SceneMap(sceneMap)});
for (let i = 0; i < tabRoutes.length; i++) {
const tabRoute = tabRoutes[i];
sceneMap[tabRoute.key] = () => {
return (
<Tab
onRef={(ref) => (this.child = ref)}
ref={(tab) => (this.tabRefs[i] = tab)}
windowId={windowId}
tabSequence={tabRoute.key}
tabLevel={level}
tabKey={tabRoute.key}
recordId={recordId}
orderSetByModal={this.state.orderSetByModal}
tabOrderBy={this.state.tabOrderBy}
></Tab>
);
};
}
};
startSortByHandler = () => {
this.setState({showSortby: true});
};
endSortByHandler = () => {
this.setState({ showSortby: false});
};
orderByFromModal = () => {
return 'creationDate asc'
}
refreshTab = () => {
this.orderByFromModal();
this.child.refresh()
}
onOKHandler = () => {
this.endSortByHandler();
const orderBy = this.orderByFromModal();
this.setState({
tabOrderBy: orderBy,
orderSetByModal: true}, () => {
this.refreshTab()
});
}
render() {
return (
<View>
<TabView
navigationState={{index: this.state.tabIndex, routes: this.state.tabRoutes}}
renderScene={this.state.renderScene}
onIndexChange={(index) => {
this.setState({ tabIndex: index });
}}
lazy
swipeEnabled={false}
renderTabBar={(props) => <TabBar {...props} />}
/>
<Sortby
visible={this.state.showSortby}
onCancel={this.endSortByHandler}
onOK={this.onOKHandler}
></Sortby>
</View>
);
}
}
export default CardView;
Child Component: Tab.js
import React from "react";
import { FlatList } from "react-native";
import { Windows } from "../stores";
import SwipeableCard from "./SwipeableCard";
class Tab extends React.Component {
constructor(props) {
super(props);
this.state = {
currentTab: null,
records: [],
refreshing: false,
};
this.listRef = null;
}
async componentDidMount() {
this.props.onRef(this);
await this.reload(this.props.recordId, this.props.tabLevel, this.props.tabSequence);
}
componentWillUnmount() {
this.props.onRef(null);
}
//I tried adding componentDidUpdate, but it did not work at all
componentDidUpdate(prevProps) {
if (this.props.orderSetByModal !== prevProps.orderSetByModal) {
this.refresh();
}
}
getOrderBy = () => {
let orderByClause;
if (this.props.orderSetByModal) {
orderByClause = this.props.tabOrderBy;
} else {
orderByClause = "organization desc";
}
return orderByClause;
};
async reload() {
const currentTab = Windows.getTab(this.props.windowId, this.props.tabSequence, this.props.tabLevel);
this.setState({ currentTab });
let response = null;
const orderBy = this.getOrderBy();
response = await this.props.entity.api.obtainRange(orderBy);
this.setState({ records: response.dataList })
}
refresh = () => {
this.setState({ refreshing: true }, () => {
this.reload(this.props.recordId, this.props.tabLevel, this.props.tabSequence)
.then(() => this.setState({ refreshing: false }));
});
};
renderTabItem = ({ item, index }) => (
<SwipeableCard
title={"Card"}
/>
);
render() {
if (!this.state.currentTab) {
return null;
}
return (
<>
<FlatList
ref={(ref) => (this.listRef = ref)}
style={{ paddingTop: 8 }}
refreshing={this.state.refreshing}
onRefresh={this.refresh}
data={this.state.records}
keyExtractor={(item) => (item.isNew ? "new" : item.id)}
/>
</>
);
}
}
export default Tab;

Adding events to ReactBigCalendar using redux

I'm currently working on a booking app, and in that regard I need to fetch some data from an API. I'm using react + redux to do this, but I can't seem to get this element BigCalendar to update when the state is updated. BigCalendar has to have some kind of object for it's init process.
BookingReducer.js
import { fetchBookingStart, fetchBookingsSuccess, fetchBookingsError } from '../types.js';
const initialState = {
fetching: false,
fetched: false,
events: [],
error: null
}
export default function (state = initialState, action) {
switch (action.type) {
case fetchBookingStart:
return {
...state,
fetching: true,
fetched: false
}
case fetchBookingsSuccess:
return {
...state,
fetching: false,
fetched: true,
events: action.payload.bookings.length < 0 ? [] : action.payload.bookings.map(B => {
return {
id:22,
title: "testTitle",
description: B.description,
start: B.dateFrom,
end: B.dateTo,
room: B.room,
user: B.user
}
})
}
case fetchBookingsError:
return {
...state,
fetching: false,
error: action.payload.error
}
default:
return state;
}
}
bookingAction.js
import axios from "axios";
import { fetchBookingStart, fetchBookingsSuccess, fetchBookingsError } from '../types.js';
const apiUrl = "http://localhost/api/booking"; //CHANGE FOR PROD!
export const getBookings = () => dispatch => {
let allUrl = apiUrl + "/find/";
dispatch({type: fetchBookingStart});
axios.get(allUrl).then(response => {
console.log(response.data);
dispatch({
type: fetchBookingsSuccess,
payload: response.data
})
}).catch(error => {
dispatch({
type: fetchBookingsError,
payload: error
});
});
}
App.js
import React, { Component } from "react";
import { connect } from 'react-redux';
import { getBookings } from './components/redux/actions/bookingActions';
import Link from "react-router-dom/Link";
import BigCalendar from 'react-big-calendar';
import moment from 'moment';
import 'react-big-calendar/lib/css/react-big-calendar.css';
import "./style.css";
import 'moment/locale/da';
import BookingDialog from './components/booking_create_dialog/BookingDialog';
import Dialog from "material-ui/Dialog/Dialog";
import FlatButton from "material-ui/FlatButton/FlatButton";
let isDialogOpen = false;
moment.locale('da');
BigCalendar.momentLocalizer(moment);
function eventStyleGetter(event, start, end, isSelected) {
let style = { backgroundColor: "" }
switch (event.room) {
case "sal":
style.borderColor = "#781B7F";
style.backgroundColor = "#781B7F";
break;
case "cafe":
style.borderColor = "#067F3D";
style.backgroundColor = "#067F3D";
break;
default:
break;
}
return { style: style };
}
class App extends Component {
componentWillMount() {
this.props.getBookings();
}
componentDidUpdate() {
if (this.props.fetched === true && this.props.fetching === false) {
this.refs.BigCalendar.forceUpdate();
}
}
render() {
return (
<div className="MainContainer">
{/*<Link to="/login"><FlatButton>Login</FlatButton></Link>*/}
<div className="CalendarContainer">
<BigCalendar
ref="BigCalendar"
selectable
className="Calendar"
events={this.props.events}
defaultView="week"
defaultDate={new Date()}
step={60}
eventPropGetter={eventStyleGetter}
/>
</div>
<div className="TestContainer">
<button onClick={() => {
this.props.events.push({
id: 55,
title: "test event",
allDay: true,
start: new Date(),
end: new Date()
}); console.log(this.props.events)
}}> bookigns </button>
{this.props.events.map(E => <h1> {E.room} </h1>)}
</div>
</div>
)
}
}
const mapStateToProps = state => ({
events: state.bookings.events,
fetched: state.bookings.fetched,
fetching: state.bookings.fetching
})
export default connect(mapStateToProps, { getBookings })(App);
Please point out any mistakes that can help me along the right way of doing this.
I was having a similar problem with my react-redux setup and realized my events array of objects wasn't formatted correctly. Other than checking this, I'd also check to see if BigCalendar is getting rendered with anything from this.props.events in the first place. Every time the events prop is changed for BigCalendar it updates itself.

Lot of repetition in React component

I have a rather large React component that manages the display of a detail for a job on my site.
There are a few things that I would like to do smarter
The component has a few options for opening Dialogs. For each dialog I have a separate Open and Close function. For example handleImageGridShow and handleImageGridClose. Is there any way to be more concise around this?
I have many presentational components (e.g. ViewJobDetails) that shows details about the job. My issue is that I have to pass them down into each Component as a prop and I'm passing the same props over and over again
As I'm loading my data from firebase I often have to do similar checks to see if the data exists before I render the component (e.g.this.state.selectedImageGrid && <ImageGridDialog />). Is there any more clever way of going about this?
import React, { Component } from 'react';
import { withStyles } from 'material-ui/styles';
import ViewJobAttachment from "../../components/jobs/viewJobAttachment";
import ViewJobDetails from "../../components/jobs/viewJob/viewJobDetails";
import ViewJobActions from "../../components/jobs/viewJob/viewJobActions";
import ViewCompanyDetails from "../../components/jobs/viewJob/viewCompanyDetails";
import ViewClientsDetails from "../../components/jobs/viewJob/viewClientsDetails";
import ViewProductsDetails from "../../components/jobs/viewJob/viewProductsDetails";
import ViewAttachmentDetails from "../../components/jobs/viewJob/viewAttachmentDetails";
import ViewEventLogDetails from "../../components/jobs/viewJob/viewEventLogDetails";
import ViewSummaryDetails from "../../components/jobs/viewJob/viewSummary";
import {FirebaseList} from "../../utils/firebase/firebaseList";
import SimpleSnackbar from "../../components/shared/snackbar";
import {calculateTotalPerProduct} from "../../utils/jobsService";
import BasicDialog from "../../components/shared/dialog";
import ImageGrid from "../../components/shared/imageGrid";
import Spinner from "../../components/shared/spinner";
import ViewPinnedImageDialog from "../../components/jobs/viewEntry/viewPinnedImage";
import {
Redirect
} from 'react-router-dom';
const styles = theme => ({
wrapper: {
marginBottom: theme.spacing.unit*2
},
rightElement: {
float: 'right'
}
});
const ImageGridDialog = (props) => {
return (
<BasicDialog open={!!props.selectedImageGrid}
handleRequestClose={props.handleRequestClose}
fullScreen={props.fullScreen}
title={props.title}
>
<ImageGrid selectedUploads={props.selectedImageGrid}
handleClickOpen={props.handleClickOpen}/>
</BasicDialog>
)
};
class ViewJob extends Component {
constructor() {
super();
this.state = {
currentJob: null,
entries: [],
promiseResolved: false,
attachmentDialogOpen: false,
openAttachment: null,
selectedImageGrid: false,
selectedPinnedImage: false,
showSnackbar: false,
snackbarMsg: '',
markedImageLoaded: false,
loading: true,
redirect: false
};
this.firebase = new FirebaseList('jobs');
this.handleJobStatusChange = this.handleJobStatusChange.bind(this);
this.handleImageGridShow = this.handleImageGridShow.bind(this);
this.handleImageGridClose = this.handleImageGridClose.bind(this);
this.handlePinnedImageClose = this.handlePinnedImageClose.bind(this);
this.handlePinnedImageShow = this.handlePinnedImageShow.bind(this);
this.handleMarkedImageLoaded = this.handleMarkedImageLoaded.bind(this);
this.handleRemove = this.handleRemove.bind(this);
this.pushLiveToClient = this.pushLiveToClient.bind(this);
}
componentDidMount() {
this.firebase.db().ref(`jobs/${this.props.id}`).on('value', (snap) => {
const job = {
id: snap.key,
...snap.val()
};
this.setState({
currentJob: job,
loading: false
})
});
const previousEntries = this.state.entries;
this.firebase.db().ref(`entries/${this.props.id}`).on('child_added', snap => {
previousEntries.push({
id: snap.key,
...snap.val()
});
this.setState({
entries: previousEntries
})
});
}
handleRemove() {
this.firebase.remove(this.props.id)
.then(() => {
this.setState({redirect: true})
})
};
pushLiveToClient() {
const updatedJob = {
...this.state.currentJob,
'lastPushedToClient': Date.now()
};
this.firebase.update(this.state.currentJob.id, updatedJob)
.then(() => this.handleSnackbarShow("Job pushed live to client"))
}
handleJobStatusChange() {
const newState = !this.state.currentJob.completed;
const updatedJob = {
...this.state.currentJob,
'completed': newState
};
this.firebase.update(this.state.currentJob.id, updatedJob)
}
handleSnackbarShow = (msg) => {
this.setState({
showSnackbar: true,
snackbarMsg: msg
});
};
handleSnackbarClose= (event, reason) => {
if (reason === 'clickaway') {
return;
}
this.setState({ showSnackbar: false });
};
handleAttachmentDialogClose =() => {
this.setState({attachmentDialogOpen: false})
};
handleClickOpen = (file) => {
this.setState({
attachmentDialogOpen: true,
openAttachment: file
});
};
handleImageGridShow(imageGrid) {
this.setState({selectedImageGrid: imageGrid})
}
handleImageGridClose() {
this.setState({selectedImageGrid: false})
}
handlePinnedImageShow(pinnedImage) {
this.setState({selectedPinnedImage: pinnedImage})
}
handlePinnedImageClose() {
this.setState({selectedPinnedImage: false})
}
handleMarkedImageLoaded() {
this.setState({markedImageLoaded: true})
}
render() {
const {classes} = this.props;
let {_, costPerItem} = calculateTotalPerProduct(this.state.entries);
if (this.state.redirect) {
return <Redirect to='/jobs' push/>
} else {
if (this.state.loading) {
return <Spinner/>
} else {
return (
<div className={styles.wrapper}>
{this.state.currentJob &&
<div>
<ViewJobActions currentJob={this.state.currentJob}
handleJobStatusChange={this.handleJobStatusChange}
pushLiveToClient={this.pushLiveToClient}
/>
<ViewJobDetails currentJob={this.state.currentJob}/>
<ViewCompanyDetails currentJob={this.state.currentJob}/>
<ViewClientsDetails currentJob={this.state.currentJob}/>
<ViewProductsDetails currentJob={this.state.currentJob}/>
{this.state.currentJob.selectedUploads && this.state.currentJob.selectedUploads.length > 0
? <ViewAttachmentDetails currentJob={this.state.currentJob} handleClickOpen={this.handleClickOpen}/>
: null}
<ViewEventLogDetails jobId={this.state.currentJob.jobId}
jobKey={this.state.currentJob.id}
entries={this.state.entries}
handlePinnedImageShow={this.handlePinnedImageShow}
handleImageGridShow={this.handleImageGridShow}/>
<ViewSummaryDetails stats={costPerItem}/>
<ViewJobAttachment open={this.state.attachmentDialogOpen}
handleRequestClose={this.handleAttachmentDialogClose}
attachment={this.state.openAttachment}
/>
{this.state.selectedImageGrid &&
<ImageGridDialog selectedImageGrid={this.state.selectedImageGrid}
handleRequestClose={this.handleImageGridClose}
handleClickOpen={this.handleClickOpen}
title="Pictures for job"
fullScreen={false}/>}
{this.state.selectedPinnedImage &&
<ViewPinnedImageDialog attachment={this.state.selectedPinnedImage}
open={!!this.state.selectedPinnedImage}
markedImageLoaded={this.state.markedImageLoaded}
handleMarkedImageLoaded={this.handleMarkedImageLoaded}
handleRequestClose={this.handlePinnedImageClose}
otherMarkedEntries={this.state.entries}
/>
}
<SimpleSnackbar showSnackbar={this.state.showSnackbar}
handleSnackbarClose={this.handleSnackbarClose}
snackbarMsg={this.state.snackbarMsg}/>
</div>}
</div>
);
}
}
}
}
export default withStyles(styles)(ViewJob);
You can define a regular component method and bind it in handler like this onSomething={this.handler.bind(this, index)} assuming you have some distinguishable thing in the index var
function should look like this
handler(index) {
...
}

React: this.setState() working in some functions, not in others within the same component

I am trying to develop a simple little survey component with its own local state. I've already successfully used this.setState() in my handleChange function to update which radio button is selected. I can see that it's working in console logs and on the live page. However, I am now trying to use the state to display a modal and highlight incomplete questions if the user tries to submit the survey without completing it. The functions I have to do this execute, but the state does not update. I am having trouble seeing any difference between where I updated state successfully and where I didn't.
Here's my container where I'm controlling state and defining the functions. I don't think any other code is relevant, but let me know if I need to include something else:
import React, { Component } from 'react'
import PropTypes from 'prop-types'
import { Redirect } from 'react-router'
import { history } from '../history'
import { connect } from 'react-redux'
import _ from 'lodash'
import { postPhq, sumPhq } from '../store'
import { Phq } from '.'
import { UnfinishedModal } from '.'
/**
* CONTAINER
*/
class PhqContainer extends Component {
constructor(props) {
super(props)
this.state = {
phq: {
q1: false, q2: false, q3: false, q4: false, q5: false,
q6: false, q7: false, q8: false, q9: false, q10: false
},
hilitRows: [],
modalOpen: false
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
this.makeButtons = this.makeButtons.bind(this)
this.toggleModal = this.toggleModal.bind(this)
}
//handles clicks on radio buttons
handleChange(question, event) {
var newPhq = this.state.phq
newPhq[question] = event.target.value
this.setState({phq: newPhq})
console.log("radio button", this.state)
}
// on submit, first check that PHQ-9 is entirely completed
// then score the PHQ-9 and dispatch the result to the store
// as well as posting the results to the database and
// dispatching them to the store
// if the PHQ-9 is not complete, open a modal to alert the user
handleSubmit(event) {
event.preventDefault()
if (this.checkCompletion()) {
this.props.sumPhq(this.sum())
this.props.postPhq(this.state.phq)
this.props.history.push('/results')
} else {
console.log(this.unfinishedRows())
this.toggleModal()
this.setState({hilitRows: this.unfinishedRows()})
}
}
// returns true if user has completed the PHQ-9 with no missing values
checkCompletion() {
return !this.unfinishedRows().length || this.oneToNine().every(val => val === 0)
}
unfinishedRows() {
return Object.keys(_.pickBy(this.state.phq, (val) => val === false))
}
oneToNine() {
var qs1to9 = Object.assign({}, this.state.phq)
delete qs1to9.q10
return Object.values(qs1to9)
}
toggleModal() {
console.log("I'm about to toggle the modal", this.state)
this.setState({modalOpen: !this.state.modalOpen})
console.log("I toggled the modal", this.state)
}
// scores the PHQ-9
sum() {
return this.oneToNine
.map(val => parseInt(val))
.reduce((total, num) => total + num)
}
makeButtons = (num, labels) => {
var question = 'q' + (num + 1).toString()
return (
<div style={rowStyle}>
{labels.map((label, i) => {
return (
<td style={{border: 'none'}}>
<div className="col radio center-text" >
<input type="radio"
value={i}
onChange={(event) => {this.handleChange(question, event)}}
checked={this.state.phq[question] && parseInt(this.state.phq[question]) == i} />
<label>{label}</label>
</div>
</td>
)
})}
</div>
)
}
render() {
return (
<div>
<Phq {...this.state} {...this.props}
handleChange={this.handleChange}
handleSubmit={this.handleSubmit}
makeButtons={this.makeButtons} />
<UnfinishedModal show={this.state.modalOpen} toggleModal={this.toggleModal} />
</div>
)
}
}
const mapDispatch = (dispatch) => {
return {
postPhq: (qs) => {
dispatch(postPhq(qs))
},
sumPhq: (total) => {
dispatch(sumPhq(total))
}
}
}
export default connect(() => { return {} }, mapDispatch)(PhqContainer)
const rowStyle = {
paddingRight: 15,
borderWidth: 0,
margin: 0,
border: 'none',
borderTop: 0
}
This line this.setState({phq: newPhq}) updates the state. This line this.setState({hilitRows: this.unfinishedRows()}) and this line this.setState({modalOpen: !this.state.modalOpen}) do not.
I had the same issue happen in my project like setState is not working in some functions but its perfect for other functions in the same component. First of all you should understand, As mentioned in the React documentation, the setState being fired synchronously. So you can check like below value being updated.
this.setState({mykey: myValue}, () => {
console.log(this.state.mykey);
});
In my case, I was tried to update the value of an event onChange with an input, in every keyUp it's trying to update, Its causes the problem for me. So I have tried to used a debounce(delay) for the function so its working fine for me. Hope this hint will help you or someone else.
this.myFunction = debounce(this.myFunction,750);
<Input onChange={this.myFunction} />

Resources