Assigning state to props from redux does not work - reactjs

import React, { Component } from 'react';
import DisplayTable from './Table.js';
class App extends Component {
constructor(props) {
super(props);
this.state = {
menuItems: this.props.menu_items,
searchString: '',
displayItems: this.props.menu_items
}
this.search = this.search.bind(this);
this.handleChange = this.handleChange.bind(this);
}
componentWillMount() {
this.props.get_menu_items_api(false);
}
componentWillReceiveProps(nextProps) {
this.setState({ menuItems: nextProps.menu_items })
}
handleChange(e, isEnter) {
const searchData = () => {
let tempMenuProductDetails = this.props.menu_items;
const filterArray = tempMenuProductDetails.reduce((result, category) => {
if (category.categoryName.toLowerCase()
.indexOf(this.state.searchString.toLowerCase()) > -1) {
result.push(category);
}
if (category.productList && category.productList.length > 0) {
category.productList = category.productList.reduce((productListResult,
productList) => {
if (!!productList.productName &&
productList.productName.toLowerCase()
.indexOf(this.state.searchString.toLowerCase()) > -1)
{
productListResult.push(productList);
}
return productListResult;
}, []);
}
return result;
}, []);
this.setState({
displayItems: filterArray
}, function () {
console.log(this.state.displayItems);
})
console.log(filterArray);
}
if (!isEnter) {
this.setState({
searchString: e.target.value
});
} else {
searchData();
}
}
search(e) {
if (e.keyCode == 13) {
this.handleChange(e, true);
}
this.handleChange(e, false);
}
render() {
console.log(this.state.displayItems);
console.log(this.props.menu_items);
console.log(this.state.menuItems);
return (
<DisplayTable dataProp={this.state.displayItems} editFuncProp=
{this.props.edit_menu_items_api} /> )
}
}
export default App;
I have this search function in this file that does not update the value of props coming from the container of redux. Now when I pass {this.state.displayItems} in menu ,it does not display the data.
But when I pass {this.props.menu_items} it displays the data and I am not able to modify this.props.menu_items on the basis of search.
I have tried this code . what should i do?

The problem seems to be that, initially this.props.menu_items is an empty array and only after some API call the value is updated and you get the returned array on the second render, thus if you use it like
<DisplayTable dataProp={this.props.menu_items} editFuncProp=
{this.props.edit_menu_items_api} />
it works. Now that you use
<DisplayTable dataProp={this.state.displayItems} editFuncProp=
{this.props.edit_menu_items_api} />
and displayItems is only initialized in the constructor which is only executed once at the time, component is mounted and hence nothing is getting displayed.
The solution seems to be that you update the displayItems state in componentWillReceiveProps and call the search function again with the current search string so that you search results are getting updated.
Code:
import React, { Component } from 'react';
import DisplayTable from './Table.js';
class App extends Component {
constructor(props) {
super(props);
this.state = {
menuItems: this.props.menu_items,
searchString: '',
displayItems: this.props.menu_items
}
this.search = this.search.bind(this);
this.handleChange = this.handleChange.bind(this);
}
componentWillMount() {
this.props.get_menu_items_api(false);
}
componentWillReceiveProps(nextProps) {
this.setState({ menuItems: nextProps.menu_items, displayItems: nextProps.menu_items })
this.handleChange(null, true);
}
handleChange(e, isEnter) {
const searchData = () => {
let tempMenuProductDetails = this.props.menu_items;
const filterArray = tempMenuProductDetails.reduce((result, category) => {
if (category.categoryName.toLowerCase()
.indexOf(this.state.searchString.toLowerCase()) > -1) {
result.push(category);
}
if (category.productList && category.productList.length > 0) {
category.productList = category.productList.reduce((productListResult,
productList) => {
if (!!productList.productName &&
productList.productName.toLowerCase()
.indexOf(this.state.searchString.toLowerCase()) > -1)
{
productListResult.push(productList);
}
return productListResult;
}, []);
}
return result;
}, []);
this.setState({
displayItems: filterArray
}, function () {
console.log(this.state.displayItems);
})
console.log(filterArray);
}
if (!isEnter) {
this.setState({
searchString: e.target.value
});
} else {
searchData();
}
}
search(e) {
if (e.keyCode == 13) {
this.handleChange(e, true);
}
this.handleChange(e, false);
}
render() {
console.log(this.state.displayItems);
console.log(this.props.menu_items);
console.log(this.state.menuItems);
return (
<DisplayTable dataProp={this.state.displayItems} editFuncProp=
{this.props.edit_menu_items_api} /> )
}
}
export default App;

Related

React: can't update the state of Status, no re-render

I have been working with react for a few weeks and have encountered a problem when trying to create a todo app. When I want to update the state of status in handleStatus(), nothing happens in the browser.
handleStatus(event) {
let newStatus;
const changeState = event.status == 'done' ? newStatus = 'open' : newStatus = 'done';
this.setState({ status: newStatus });
Why I can't update this state like I did with the others? Does anyone have a solution?
Thank you very much.
Here is the full code:
import React from "react";
import { InputBar } from "./InputBar";
import { Todo } from "./Todo";
const emptyForm = {
enterTodo: ""
};
export class TodoTable extends React.Component {
constructor(props) {
super(props);
this.state = {
enterTodo: "",
todos: this.props.todos,
status: 'open'
};
this.handleEnterTodo = this.handleEnterTodo.bind(this);
this.handleStatus = this.handleStatus.bind(this);
this.handleCreateTodo = this.handleCreateTodo.bind(this);
this.handleClearTodos = this.handleClearTodos.bind(this);
this.handleDeleteTodo = this.handleDeleteTodo.bind(this);
}
//Textbox Input handler
handleEnterTodo(event) {
this.setState({
enterTodo: event.target.value
});
}
//Status handler
handleStatus(event) {
let newStatus;
const changeState = event.status == 'done' ? newStatus = 'open' : newStatus = 'done';
this.setState({ status: newStatus });
}
//delete todo
handleDeleteTodo(event) {
let todo = this.state.todos;
todo.splice(this.state.todos.indexOf(event), 1)
this.setState({ todo });
}
//Create Todo
handleCreateTodo(event) {
const todo = {
id: this.state.todos.length,
describtion: this.state.enterTodo,
status: 'open'
};
this.setState({
todos: [todo, ...this.state.todos]
})
this.state.enterTodo = emptyForm.enterTodo; // Überarbeiten
}
//Clear Todo List
handleClearTodos(event) {
let CleanedTodos = []
this.state.todos.forEach((element, index) => {
if(this.state.todos[index].status == 'open'){
CleanedTodos.push(this.state.todos[index]);
}
});
this.setState({
todos: CleanedTodos
});
}
render() {
return (
<>
<InputBar
handleCreateTodo={ this.handleCreateTodo }
handleEnterTodo={ this.handleEnterTodo }
enterTodo={ this.state.enterTodo }
handleClearTodos={ this.handleClearTodos }
/>
<Todo
handleStatus={ this.handleStatus }
todos={ this.state.todos }
handleClearTodos={ this.state.handleClearTodos }
handleDeleteTodo= { this.handleDeleteTodo }
/>
</>
);
}
}
Remember if your are keeping the status of done in this component then all the todos in the todo table will show they are of the status done
the best way would be each todo having its own local state of done so that each done state is unique and then handle it something like this
<p value="heyy" onClick={(e) => console.log(e.target.getAttribute("value"))}>Something</p>
OR
const Todo = (props) => {
const [done, setDone] = useState(false)
return <p onclick={() => setDone(true)} >{todo}</p>
}
todos.map(todo => {
return <Todo />
})

how to update component state when rerendering

Hi I am trying to change the state of a component during the render. The state should change the classname depending on the list passed to it as props. I have tried but it does not seem to work. I can pass props but not change the state.
class Square extends React.Component {
constructor(props) {
super(props);
this.state = {alive: true};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
alive: !state.alive
}));
};
render() {
return <div className = { this.state.alive ? "square--green" : "square--grey" } onClick = { this.handleClick } />;
};
}
function SquareList(props) {
const oxGrid = props.oxGrid;
const listItems = [];
oxGrid.forEach((item, i) => {
if(item === 'O'){
listItems.push(<Square key= {i}/>)
}
else {
listItems.push(<Square key = {i} />)
}
});
return listItems;
};
let printer = (function () {
let print = function (oXGrid) {
return ReactDOM.render(<SquareList oxGrid ={oXGrid} />, grid);
};
return { print: print };
})();
I have made the following changes in Square and SquareList Component. You need to pass a prop item to the Square Component.
class Square extends React.PureComponent {
constructor(props) {
super(props);
const isALive = this.props.item === 'O';
this.state = {
alive: isALive
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState(state => ({
alive: !state.alive
}));
};
componentWillReceiveProps(nextProps) {
if(this.props.item !== nextProps.item) {
this.setState({
alive: nextProps.item === '0'
});
}
}
render() {
return <div className = { this.state.alive ? "square--green" : "square--grey" } onClick = { this.handleClick } />;
};
}
function SquareList(props) {
const oxGrid = props.oxGrid;
const listItems = oxGrid.map((item, i) => {
return(
<Square item={item} key= {i}/>
)
});
return listItems;
};
let printer = (function () {
let print = function (oXGrid) {
return ReactDOM.render(<SquareList oxGrid ={oXGrid} />, grid);
};
return { print: print };
})();

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) {
...
}

Why does my data disappear when a subscription goes through?

Why am I getting undefined for data when the subscription goes through?
I am trying to figure out where the undefined for my props.data.allLocations is coming from. Any help would be appreciated.
//Higher order component
export const LocationList = graphql(
gql`
query ($site: ID!) {
allLocations(
filter: {
site: {
id:$site
}
}
) {
id
name
}
}
`,
{
options: (ownProps)=>({
variables: {
site: ownProps.site
},
}),
//props were injected from the JSX element
props: props => {
return {
data: props.data,
subscribeToData: params => {
return props.data.subscribeToMore({
document:
gql`
subscription newLocations {
Location {
mutation
node {
id
name
}
}
}
`,
variables: {
//Empty for now
//site: props.site,
},
updateQuery: (previousState, {subscriptionData}) => {
if (!subscriptionData.data) {
return previousState;
}
var newArray =[subscriptionData.data.Location.node].concat(previousState.allLocations)
var newState = {
...previousState,
allLocations: [
{
...subscriptionData.data.Location.node
},
...previousState.allLocations
],
};
return newState
}
})
},
}
},
onError: (err) => console.error(err)
} )(EntityList)
//List Component
class EntityList extends Component {
componentWillReceiveProps(newProps) {
if (!newProps.data.loading) {
console.log(newProps)
if (this.subscription && this.props.hasOwnProperty('subscribeToData')) {
if (newProps.data.allLocations !== this.props.data.allLocations) {
console.log("Resubscribe")
// if the todos have changed, we need to unsubscribe before resubscribing
this.subscription()
} else {
console.log('else')
// we already have an active subscription with the right params
return
}
}
this.subscription = this.props.subscribeToData(newProps)
}}
render () {
if (this.props.data.loading) {
return (<div>Loading</div>)
}
var Entities = [];
for(var key in this.props.data) {
if(this.props.data[key] instanceof Array){
Entities = Entities.concat(this.props.data[key])
//console.log(this.props.data[key])
}
}
return (
<div className='w-100 flex justify-center bg-transparent db' >
<div className='w-100 db' >
{Entities.map((entity) =>
(
<EntityListView
user={this.props.user}
key={entity.id}
entityId={entity.id}
name={entity.name}
profilePic={(entity.profilePic)?entity.profilePic.uuid : this.props.defaultPic.uuid}
clickFunc={this.props.clickFunc}
/>
))}
</div>
</div>
)
}
}
Thanks to all who looked into this.
I got it to work by splitting up my queries as suggested by #nburk.
I was able to keep it modular by creating my own high order component.
If anyone is interested:
const Subscriber = (document, config) => {
return (WrappedComponent) => {
return class extends Component {
constructor(props) {
super(props)
this.state={}
this.subscription = null
}
componentWillReceiveProps(nextProps) {
console.log(nextProps)
if (!this.subscription && !nextProps.data.loading) {
console.log("Sucess")
let { subscribeToMore } = this.props.data
this.subscription = [subscribeToMore(
{
document: document,
updateQuery: (previousResult, { subscriptionData }) => {
console.log(subscriptionData)
var newResult = [subscriptionData.data[config.modelName].node].concat(previousResult[config.propName])
console.log(newResult)
return {
//"allItems"
[config.propName]: newResult,
}
},
onError: (err) => console.error(err),
}
)]
this.setState({});
}
}
render () {
if (this.props.data.loading) {
return (<div>Loading</div>)
}
return (
<WrappedComponent {...this.props} />
)
}
}
}
}
export default Subscriber
/*prop config = {
propName: "string", //allItems // from query
//so I do not have to parse the gql query (would have to recieve from parent)
modelName: "string" //Item
// from subscribe //so I do not have to parse the gql subscribe
}
*/
I now wrap my component like this:
export const LocationList = graphql(gql`...,
{options: (ownProps)=>({
variables: {
site: ownProps.site
}})})(
Subscriber(gql`...,
propName:"allLocations",
modelName:"Location",
)(EntityList))
Thanks

React JS - updating state within an eventListener

I'm trying to update the state of my component inside of an eventListener. I'm getting the following console error:
'Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Header component'
This is my component code:
class Header extends React.Component {
constructor(props) {
super(props);
this.state = {
fixed: false
}
}
handleScroll(event) {
this.setState({
fixed: true
});
}
componentDidMount() {
window.addEventListener("scroll",() => {
this.handleScroll();
});
}
componentWillUnmount() {
window.removeEventListener("scroll",() => {
this.handleScroll();
});
}
render() {
var {
dispatch,
className = "",
headerTitle = "Default Header Title",
onReturn,
onContinue
} = this.props;
var renderLeftItem = () => {
if (typeof onReturn === 'function') {
return (
<MenuBarItem icon="navigation-back" onClick={onReturn}/>
)
}
};
var renderRightItem = () => {
if (typeof onContinue === 'function') {
return (
<MenuBarItem icon="navigation-check" onClick= {onContinue}/>
)
}
};
return (
<div className={"header " + className + this.state.fixed}>
{renderLeftItem()}
<div className="header-title">{headerTitle}</div>
{renderRightItem()}
</div>
)
}
}
Header.propTypes = {
};
let mapStateToProps = (state, ownProps) => {
return {};
};
export default connect(mapStateToProps)(Header);
IMHO this is because you do ont unregister the function as you expect it, and a scroll event is sent after an instance of this component has been unmounted
try this:
componentDidMount() {
this._handleScroll = this.handleScroll.bind(this)
window.addEventListener("scroll", this._handleScroll);
}
componentWillUnmount() {
window.removeEventListener("scroll", this._handleScroll);
}

Resources