Map function won't work after react state update - javascript

Hi everyone,
I have a map function that maps a data array inside one of my state's. The map function works fine on the first load, but when I start 'pushing' data in the array the following error appears:
TypeError: Cannot read property 'map' of undefined
I don't know what to do next since I absolutely don't know what I'm doing wrong here.
My component:
import React, { Component } from 'react';
import { Button, Table, Input, InputGroup, Container } from 'reactstrap';
import { Person } from './components/Person';
import { getFetch, postFetch } from './utilities/ApiCalls';
export default class App extends Component {
state = {
fetchData: null,
success: undefined,
name: undefined,
birthday: undefined
};
async componentDidMount() {
const response = await getFetch('http://127.0.0.1:8000/api/birthday/all');
this.setState({
fetchData: response
});
}
addPerson = async () => {
const { name, birthday, fetchData } = this.state;
const response = await postFetch('http://127.0.0.1:8000/api/birthday/create', {
name: name,
birthday: birthday
});
this.setState({
fetchData: [...fetchData.data, {
id: response.data.id,
naam: response.data.naam,
geboortedatum: response.data.geboortedatum
}]
});
};
render() {
const { fetchData } = this.state;
return (
<Container>
<Table>
<thead>
<tr>
<th>Name</th>
<th>Date</th>
<th>Age</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
{fetchData ? fetchData.data.map((person) => (
<Person key={person.id} name={person.naam} date={person.geboortedatum}/>
)) : <Person name="Loading..." date="0"/>
}
</tbody>
</Table>
<InputGroup>
<Input type="text" onChange={(e) => this.setState({ name: e.target.value })}/>
<Input type="date" onChange={(e) => this.setState({ birthday: e.target.value })}/>
</InputGroup>
<Button onClick={this.addPerson}>Add Person</Button>
</Container>
);
}
}
Any help is appreciated!

Initially, from your render method you hope fetchData is to be an object with data as a key name which would be an array. But your addPerson function changes this.state.fetchData to an array. You can update your setState in addPerson to be
fetchData: { data: [...fetchData.data, { id: res.data.id ... }] }

Related

Why doesn't the table appear?

components/App.js
import React from 'react';
import { connect } from 'react-redux'
import { add_task } from '../actions/index';
class App extends React.Component {
state = {
text: '',
time: ''
}
render_tasks = () => {
const { tasks } = this.props
return (
<table>
<tbody>
{tasks.map(task => {
return (
<tr key={task.id}>
<td>{task.text}</td>
<td>{task.time}</td>
</tr>
)
})
}
</tbody>
</table>
)
}
render() {
console.log('App props', this.props)
return (
<div className="App">
<input type='text'
onChange={(e) => this.setState({
text: e.target.value
})} />
<input type='time'
onChange={(e) => this.setState({
time: e.target.value
})} />
<button
onClick={() => this.props.add_task(
this.state.text, this.state.time)}>
Add
</button>
{this.render_tasks()}
</div>
);
}
}
function mapStateToProps(state) {
return {
tasks: state
}
}
function mapDispatchToProps(dispatch) {
return {
add_task : () => dispatch(add_task())
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App);
actions/index.js
import { ADD_TASK } from './../types';
export const add_task = (text, time) => {
const action = {
type: ADD_TASK,
text,
time
}
console.log('Add action', action)
return action
}
reducers/index.js
import { ADD_TASK } from './../types';
const tasks = (state=[], action) => {
let tasks = [];
if (action.type === ADD_TASK) {
tasks = [...state, {
text: action.text,
time: action.time,
id: Math.random()
}]
console.log('Data from reducer', tasks)
return tasks
} else {
return state
}
}
export default tasks;
When I click the button I expect to get a table with the information I entered in the input fields, but nothing appears, I tried replacing the table part in render_tasks function in App.js with an unordered list and the map returns a list item including 2 spans one for the text and the other for the time but all I got is the dot of the list item!
In
add_task : () => dispatch(add_task())
You don't pass any arguments to add_task().
You can explicitly define the arguments:
add_task : (text, time) => dispatch(add_task(text, time))

TypeError: Cannot read property 'map' of undefined and a walk around

there is an object contactBook defined as below. I send it to redux and get it back in the exactly same format.
{“Book1” : [{name: “Bob”},{name, “Jane”}, {name, “Mary”]}
I intended to transfer it to a name list
import React, {Component} from 'react'
import {bindActionCreators} from "redux";
import * as actions from "../redux/actions";
import {withRouter} from 'react-router'
import {connect} from 'react-redux'
class ListContactComponent extends Component {
constructor(props) {
super(props);
this.state = {
message: null
};
}
componentDidMount() {
this.props.startLoadingContacts(this.props.match.params.bookName);
}
addContactClicked = () => {
this.props.history.push({
pathname: `/addressBook/contact/`,
state: this.state.bookName
})
};
render() {
let contacts = Object.values(this.props.contacts).flat();
return (
<div className="container">
<h3>All Contacts</h3>
{this.state.message && <div class="alert alert-success">{this.state.message}</div>}
<div className="container">
<table className="table">
<thead>
<tr>
<th>Name</th>
<th>Phone Number</th>
</tr>
</thead>
<tbody>
{
contacts.map(
(contact, index) =>
<tr key={index}>
<td>{contact.name}</td>
<td>{contact.phoneNumber}</td>
</tr>
)
}
</tbody>
</table>
<div className="row">
<button className="btn btn-success" onClick={this.addContactClicked}>Add</button>
</div>
</div>
</div>
)
}
}
function mapStateToProps(state) {
return {
contacts: state.contacts
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(actions, dispatch)
}
const connectedContactList = withRouter(connect(mapStateToProps, mapDispatchToProps)(ListContactComponent));
export {connectedContactList as ListContactComponent};
if I use:
contacts = contactsBook[Book1]
I got TypeError: Cannot read property 'map' of undefined
what’s the cause of this error, and how to fix it?
if I don't use the objected returned from redux, it just works fine. I don't really know what's difference?
Actions:
export function startLoadingContacts(addressBookName) {
return (dispatch) => {
return AddressBookDataService
.retrieveContacts(addressBookName)
.then(
(response) => {
let contacts = {};
contacts[addressBookName] = response.data;
dispatch(loadContacts(contacts))
}).catch((error) => {
console.log(error)
})
}
}
export function loadContacts(contacts) {
return {
type: 'LOAD_CONTACTS',
contacts
}
}
Reducer:
function contacts(state = {}, action) {
switch (action.type) {
case 'ADD_CONTACT':
return "....";
case 'LOAD_CONTACTS':
return action.contacts;
default:
return state
}
}
console log:
contactsBook:
{Book1: Array(3)}
Book1: Array(3)
0: {name: "Bob"}
1: {name: "Jane"}
2: {name: "Mary"}
length: 3
__proto__: Array(0)
__proto__: Object
contacts:
(3) [{…}, {…}, {…}]
0: {name: "Bob"}
1: {name: "Jane"}
2: {name: "Mary"}
length: 3
or
if I use: 
 contacts = Object.values(contactsBook),
there is no output.
console log:
[Array(3)]
0: Array(3)
0: {name: "Bob"}
1: {name: "Jane"}
2: {name: "Mary"}
length: 3
__proto__: Array(0)
length: 1
when using JSON.stringy(contacts),
it prints:
[[ {name: "Bob"}
,..]] rather than [{name: "Bob"},..
 ]
In this case, How to get rid of the outer []?
if mocking up a data warper =[[data]], I can remove the outer layer by warper[0].
but it doesn't work for
contacts = Object.values(contactsBook)
contacts[0]
finally flat() solved this problem
contacts = Object.values(contactsBook).flat()
Could you please help explain the reason?
If I had to guess, you need to add initial state to your reducer that isn't an empty object, like an empty array []. This way when the component first renders and is connected to redux, it'll have a defined value that is valid to map over.
edit
Ok, so your state shape was {[book: string]: string[]}. In this case the initial state ({}) for the reducer was fine and you do need to grab the book name from the route params. Here I've updated the mapStateToProps function to also pull in the component's own props and do the computation to return the contactList as a prop to the component.
/edit
Reducer
const initialState = {};
function contacts(state = initialState, action) {
switch (action.type) {
case 'ADD_CONTACT':
return "....";
case 'LOAD_CONTACTS':
return action.contacts;
default:
return state
}
}
Component
const { contactList } = this.props;
...
contactList.map(...
...
function mapStateToProps(state, ownProps) {
const { match: { params: { bookName } } = ownProps;
return {
contactList: state.contacts[bookName] || [],
}
}
Alternative Solution Guard Pattern
{
contacts && contacts.map(
(contact, index) => (
<tr key={index}>
<td>{contact.name}</td>
<td>{contact.phoneNumber}</td>
</tr>
))
}
Change your map function to this:
{contacts["Book1"].map((contact, index) => (
<tr key={index}>
<td>{contact.name}</td>
<td>{contact.phoneNumber}</td>
</tr>
))}
Code Sandbox: https://codesandbox.io/s/react-example-pevdn

How to edit information of document in databse using React + Firebase? Can't call setState on a component that is not yet mounted

I use react and firebase for my project. Firstly, i render some information of user but then i want to edit it by clicking "edit" i get mistake:
Can't call setState on a component that is not yet mounted. This is a
no-op, but it might indicate a bug in your application. Instead,
assign to this.state directly or define a state = {}; class
property with the desired state in the EditBookComponentForm
component.
Then you clik to edit button must render EditBookComponentForm and first value of input raws must be like in database. How to fix that mistake?
import React, {Component} from 'react';
import firebase from '../firebase/firebase.js';
import AddBookComponentForm from '../addBookComponentForm/AddBookComponentForm'
import EditBookComponentForm from '../editBookComponentForm/EditBookComponentForm'
export default class BooksComponent extends Component{
EditBookComponentForm = new EditBookComponentForm();
constructor(props) {
super(props)
this.state = {
books: null,
status: false
}
this.getBook = this.getBook.bind(this);
}
componentDidMount() {
this.getBook();
}
getBook =() =>{
const newArray = [];
const selfThis = this;
console.log("i am working")
const db = firebase.firestore();
db.settings({
timestampsInSnapshots: true
});
db.collection("LibraryDB").where("user", "==",
firebase.auth().currentUser.uid)
.get()
.then(function(querySnapshot) {
querySnapshot.forEach(function(doc) {
console.log(doc.id, " => ", doc.data());
let bookWithId = doc.data()
bookWithId.id = doc.id
newArray.push(bookWithId);
});
//console.log(newArray);
selfThis.setState({
books: newArray
});
console.log("My work has ended")
})
.catch(function(error) {
console.log("Error getting documents: ", error);
});
};
deleteBook = id => {
const db = firebase.firestore();
this.setState(prevState => ({
books: prevState.books.filter(el => el.id !== id)
}));
db.collection("LibraryDB").doc(id).delete()
.then(function() {
console.log("Document successfully deleted!");
}).catch(function(error) {
console.error("Error removing document: ", error);
});
};
editBook = (id,auth,name) =>{
this.EditBookComponentForm.updateState(id,auth,name);
};
renderBooks(arr) {
console.log("items",arr)
return arr.map(book => {
return (
<tr key={book.id}>
<td>
<p>{book.author}</p>
<p>{book.bookName}</p>
<button
onClick= {() => { this.editBook(book.id, book.author, book.bookName) }}>
Edit
</button>
<button
onClick={() => { this.deleteBook(book.id) }}>
Delete
</button>
</td>
</tr>
);
});
}
render(){
if(!this.state.books){
return <p>0000000</p>;
}
return(
<div>
<AddBookComponentForm updateBooksComponent={this.getBook} />
{this.state.status ? <EditBookComponentForm/> : <null/>}
<table>
<tbody>
<tr>
<th>Author </th>
<th>Book name</th>
</tr>
{this.renderBooks(this.state.books)}
</tbody>
</table>
</div>
)};
};
Second file:
import React, { Component } from 'react';
import firebase from '../firebase/firebase.js';
export default class EditBookComponentForm extends Component{
state = {
bookName:'',
author:'',
id:''
};
updateState(id,auth,name){
this.setState({
bookName: name,
author: auth,
id: id
})
};
onChangeInputBookName = (event) => {
this.setState({bookName: event.target.value})
};
onChangeInputAuthor = (event) => {
this.setState({author: event.target.value})
};
editBook = (id) =>{
const db = firebase.firestore();
db.collection("LibraryDB").doc(id).set({
bookName: this.state.bookName,
author: this.state.author
})
.then(function() {
console.log("Document successfully written!");
})
.catch(function(error) {
console.error("Error writing document: ", error);
});
};
render(){
return(
<div>
<form className="null">
<input type='text'
value = {this.state.author}
onChange ={ this.onChangeInputAuthor }/>
<input type='text'
value = {this.state.bookName}
onChange ={ this.onChangeInputBookName }/>
<button
onClick={() => { this.editBook(this.state.id) }}>
Edit
</button>
</form>
</div>
)} ;
};
So, I would not clone & update the state from this. reference, you should pass down the props to the <EditBookComponentForm {...desiredProps} />
So for example:
editBook = (id, auth, name) =>{
this.setState({ bookprops: { bookName: id, author: auth, bookName: name } });
};
{this.state.status ? <EditBookComponentForm editProps={this.state.bookprops} /> : <null/>}
And then you can in your EditBookComponentForm component reach the passed in props by this.props.editProps
Which means below can be removed in your EditBookComponentForm
updateState(id,auth,name){
this.setState({
bookName: name,
author: auth,
id: id
})
};
The error tells you that you tried to set a state before it was initially set up in EditBookComponentForm. So add a constructor to that component and set the state inside it like so:
constructor() {
this.state = {
bookName:'',
author:'',
id:''
};
}

Sorting a specific column

I have an array items[] which has four fields name, origin, destination, seats.
I would like to sort the name alphabatically onClick of the table heading i.e Name
heres my snippet of code
JS file with array declaration variables and passing the values to form.js
Stuff.js
import React, { Component } from 'react';
import './App.css';
import Tab from './Table';
import Form from './Form';
class Stuff extends Component {
constructor() {
super();
this.state = {
name: '',
origin: '',
destination: '',
seats: '',
items: []
}
};
handleFormSubmit = (e) => {
e.preventDefault();
let items = [...this.state.items];
items.push({
name: this.state.name,
origin: this.state.origin,
destination: this.state.destination,
seats: this.state.seats
});
this.setState({
items,
name: '',
origin: '',
destination: '',
seats: ''
});
};
handleInputChange = (e) => {
let input = e.target;
let name = e.target.name;
let value = input.value;
this.setState({
[name]: value
})
};
render() {
return (
<div className="App">
<Form handleFormSubmit={ this.handleFormSubmit }
handleInputChange={ this.handleInputChange }
newName={ this.state.name }
newOrigin={ this.state.origin }
newDestination={ this.state.destination }
newSeats={ this.state.seats } />
<Tab items={ this.state.items }/>
</div>
);
}
}
export default Stuff;
Table.js
import React, { Component } from 'react';
import { Table } from 'reactstrap';
class Tab extends React.Component {
render() {
const items = this.props.items;
return (
<Table striped>
<thead>
<tr>
<th >Name</th>
<th>Origin</th>
<th>Destination</th>
<th>Seats</th>
</tr>
</thead>
<tbody>
{items.map(item => {
return (
<tr>
<td>{item.name}</td>
<td>{item.origin}</td>
<td>{item.destination}</td>
<td>{item.seats}</td>
</tr>
);
})}
</tbody>
</Table>
);
}
}
export default Tab;
Is there any way that when I click on Name Heading in my table it would sort according to the name?
Thank You
I don't go into details of ReactJS, you need to implement yourself. The idea is quite simple:
You create a event handler for header like (onClick)="sortByName()"
Define your function sortByName by passing your data into it, and sort it manually, you can use Array.sort() to achieve this.
Update the state will make React re-render the part have the update
I hope this answers your query:
const items = [
{
name: 'C',
quantity: 2
},
{
name: 'B',
quantity: 3
},
{
name: 'A',
quantity: 8
}
];
console.log(items);
items.sort((a,b) => {
const name1 = a.name.toLowerCase(), name2 = b.name.toLowerCase();
return name1 === name2 ? 0 : name1 < name2 ? -1 : 1;
});
console.log(items);
https://jsfiddle.net/abhikr713/r6L2npfL/1/

How to select all checkboxes in React?

I have this module:
import React, { Component } from 'react'
import EmailListItem from './EmailListItem'
import { createContainer } from 'meteor/react-meteor-data'
import { Emails } from '../../../../../imports/collections/emails/Emails'
class EmailList extends Component {
constructor (props) {
super(props)
this.state = {
selectedEmails: new Set(),
checked: false
}
}
handleSelectedEmails (selectedEmail, checked) {
let selectedEmails = this.state.selectedEmails
if (checked) {
selectedEmails.add(selectedEmail)
} else {
selectedEmails.delete(selectedEmail)
}
this.setState({selectedEmails})
console.log('selectedEmails', this.state.selectedEmails)
}
removeSelected () {
const selectedEmails = Array.from(this.state.selectedEmails)
Meteor.call('emails.remove', selectedEmails, (err, result) => {
if (err) console.log(err)
if (result) console.log(result)
})
}
checkedClick () {
this.setState({checked: !this.state.checked})
console.log('chcekedClick')
}
renderList () {
console.log(this.props)
return this.props.emails.map(email => {
console.log(email)
const { name, opr, ctr, _id } = email
const createdAt = email.createdAt.toDateString()
const link = `/dashboard/emailpreview/${_id}`
return (
<EmailListItem
selecetedAllEmails={this.state.checked}
handleSelectedEmails={this.handleSelectedEmails.bind(this)}
name={name}
createdAt={createdAt}
opr={opr}
ctr={ctr}
link={link}
key={email._id}
id={email._id} />
)
})
}
render () {
// TODO: make checks with state
return (
<div className="email_list">
<table>
<thead>
<tr>
<td><input onChange={this.checkedClick.bind(this)} type="checkbox" checked={this.state.checked} /></td>
<td>Title<button onClick={this.removeSelected.bind(this)} className="btn btn-danger">Remove</button></td>
<td>Dates</td>
<td>Open Rates</td>
<td>CTA</td>
</tr>
</thead>
<tbody>
{this.renderList()}
</tbody>
</table>
</div>
)
}
}
export default createContainer(() => {
Meteor.subscribe('emails')
return { emails: Emails.find({}).fetch() }
}, EmailList)
And it renders this module
import React, { Component } from 'react'
import { Link } from 'react-router'
class EmailListItem extends Component {
constructor (props) {
super(props)
this.state = {
checked: false
}
}
checkedClick () {
this.setState({checked: !this.state.checked})
console.log('chcekedClick')
}
componentDidUpdate () {
console.log('componentDidUpdate')
const { myCheckbox } = this.refs
console.log('myCheckbox', myCheckbox)
console.log('myCheckbox.name', myCheckbox.name)
console.log('myCheckbox.checked', myCheckbox.checked)
if (this.props.selecetedAllEmails) {
console.log('componentDidUpdate IF')
this.checkedClick()
this.props.handleSelectedEmails(myCheckbox.name, myCheckbox.checked)
}
}
render () {
console.log('_id', this.props.id)
return (
<tr>
<td><input ref="myCheckbox"
onChange={(event) => {
this.checkedClick()
this.props.handleSelectedEmails(event.target.name, event.target.checked)
}}
checked={this.state.checked}
type="checkbox" name={this.props.id} /></td>
<td><Link to={this.props.link}>{this.props.name}</Link></td>
<td>{this.props.createdAt}</td>
<td>Open Rates</td>
<td>CTA</td>
</tr>
)
}
}
export default EmailListItem
As you can see, for each email item I have a checkbox. I can select a few checkboxes, and click that remove button which will call remove my selected items. Now in the top I have a checkbox which should select all the checkboxes. My solution to this was to store the global checkbox checked and pass it as a prop to all the items. Then in the items I perform a check on componentDidUpdate and if the global checkbox is selected then I check that item as well. But this results in an infinite loop. What would be the best solution here?
While some of the answers provided the specific functionality of selecting all the checkboxes, I needed also common functionalities like deselecting all, selecting all then deselecting some, when manually selecting all the select all box checks on as well etc... So I wrote all of that and post it as an answer here. Thanks to everyone who replied. This code is based on Mayank Shuklas answer. Note that it may not still be perfect as I didn't properly tested it yet and definitely it needs some refactoring.
import React, { Component } from 'react'
import EmailListItem from './EmailListItem'
import { createContainer } from 'meteor/react-meteor-data'
import { Emails } from '../../../../../imports/collections/emails/Emails'
class EmailList extends Component {
constructor (props) {
super(props)
this.state = {
selectedEmails: new Set(),
checked: false
}
}
handleSelectedEmails (allSelected, individualSelected, selectedEmail, checked) {
console.log('allSelected', allSelected)
console.log('individualSelected', individualSelected)
console.log('selectedEmail', selectedEmail)
console.log('checked', checked)
let selectedEmails = this.state.selectedEmails
if (allSelected && !individualSelected) {
this.props.emails.forEach((email) => {
selectedEmails.add(email._id)
})
} else if (!allSelected && !individualSelected) {
selectedEmails.clear()
} else if (individualSelected) {
if (checked) {
selectedEmails.add(selectedEmail)
if (selectedEmails.size === this.props.emails.length) {
this.checkAll()
}
} else {
selectedEmails.delete(selectedEmail)
this.setState({checked})
}
}
this.setState({selectedEmails})
console.log('selectedEmails', this.state.selectedEmails)
}
removeSelected () {
const selectedEmails = Array.from(this.state.selectedEmails)
Meteor.call('emails.remove', selectedEmails, (err, result) => {
if (err) console.log(err)
if (result) console.log(result)
})
}
checkAll () {
this.setState({checked: !this.state.checked})
console.log('chcekedClick', this.state.checked)
this.handleSelectedEmails(!this.state.checked, false)
}
renderList () {
console.log(this.props)
return this.props.emails.map(email => {
// console.log(email)
const { name, opr, ctr, _id } = email
const createdAt = email.createdAt.toDateString()
const link = `/dashboard/emailpreview/${_id}`
return (
<EmailListItem
handleSelectedEmails={this.handleSelectedEmails.bind(this)}
name={name}
createdAt={createdAt}
opr={opr}
ctr={ctr}
link={link}
key={email._id}
id={email._id}
value={this.state.checked || this.state.selectedEmails.has(email._id)} />
)
})
}
render () {
// TODO: make checks with state
return (
<div className="email_list">
<table>
<thead>
<tr>
<td><input onChange={this.checkAll.bind(this)} type="checkbox" checked={this.state.checked} /></td>
<td>Title<button onClick={this.removeSelected.bind(this)} className="btn btn-danger">Remove</button></td>
<td>Dates</td>
<td>Open Rates</td>
<td>CTA</td>
</tr>
</thead>
<tbody>
{this.renderList()}
</tbody>
</table>
</div>
)
}
}
export default createContainer(() => {
Meteor.subscribe('emails')
return { emails: Emails.find({}).fetch() }
}, EmailList)
And the EmailListItem
import React, { Component } from 'react'
import { Link } from 'react-router'
class EmailListItem extends Component {
render () {
console.log('_id', this.props.id)
return (
<tr>
<td><input ref="myCheckbox"
onChange={(event) => {
this.props.handleSelectedEmails(false, true, event.target.name, event.target.checked)
}}
checked={this.props.value}
type="checkbox" name={this.props.id} /></td>
<td><Link to={this.props.link}>{this.props.name}</Link></td>
<td>{this.props.createdAt}</td>
<td>Open Rates</td>
<td>CTA</td>
</tr>
)
}
}
export default EmailListItem
I think, maintaining individual states for each email id is not required, you are already storing the values in parent component, pass the value from parent in props, other thing is for selecting all email ids, you are maintaining a bool in parent, at the time of passing the value in props check that bool, if the bool is true then pass true otherwise check in the set and pass the result returned by set.
Check the working solution of jsfiddle: https://jsfiddle.net/h17mcjwa/
try this renderList method:
renderList () {
return this.props.emails.map(email => {
const { name, opr, ctr, _id } = email
const createdAt = email.createdAt.toDateString()
const link = `/dashboard/emailpreview/${_id}`
return (
<EmailListItem
handleSelectedEmails={this.handleSelectedEmails.bind(this)}
name={name}
createdAt={createdAt}
opr={opr}
ctr={ctr}
link={link}
key={email._id}
id={email._id}
value={this.state.checked || this.state.selectedEmails.has(email._id)}
/>
)
})
}
And use this component:
class EmailListItem extends Component {
constructor (props) {
super(props)
//this.state = {
// checked: false
//}
}
//checkedClick () {
// this.setState({checked: !this.state.checked})
// console.log('chcekedClick')
//}
//componentDidUpdate () {
// if (this.props.selecetedAllEmails) {
// this.checkedClick()
// this.props.handleSelectedEmails(myCheckbox.name, myCheckbox.checked)
// }
//}
render () {
return (
<tr>
<td><input ref="myCheckbox"
onChange={(event) => {
this.props.handleSelectedEmails(event.target.name, event.target.checked)
}}
checked={this.props.value}
type="checkbox" name={this.props.id} /></td>
<td><Link to={this.props.link}>{this.props.name}</Link></td>
<td>{this.props.createdAt}</td>
<td>Open Rates</td>
<td>CTA</td>
</tr>
)
}
}
Let me know if it doesn't work for u.
You could use componentWillReceiveProps instead of componentDidUpdate:
class EmailListsItem extends Component {
// ...
componentWillReceiveProps (nextProps) {
const { myCheckbox } = this.refs
// if selecetedAllEmails is updated from false to true
if (nextProps.selecetedAllEmails && !this.props.selecetedAllEmails) {
this.checkedClick()
this.props.handleSelectedEmails(myCheckbox.name, myCheckbox.checked)
}
}
// ...
}

Categories

Resources