I am trying to make a react messaging app where the channel page is composed a channel bar Channel.js (Parent Component) with a general and random channel and a message-list ChannelMessage.js (Child Component).
Currently, I can click on the channel bar and it changes the url and this.props.channelName, but the child component displays the same text, regardless of Link clicked. I believe it is because ComponentDidMount does not get called in the child component. How would I go about updating/rerendering the child component to get ComponentDidMount to reload?
Channel.js
export default class Channel extends React.Component {
constructor(props) {
super(props);
this.state = {
channelName: 'general'
};
this.handleSignOut = this.handleSignOut.bind(this);
}
...
render() {
return (
<div className="container">
<div className="row">
<div className="channel-list col-lg-2">
<h2>Channels</h2>
<ul className="list-group">
<li><Link to="/channel/general"
onClick={() => this.setState({ channelName: 'general' })}>General</Link></li>
<li><Link to="/channel/random"
onClick={() => this.setState({ channelName: 'random' })}>Random</Link></li>
</ul>
<div className="footer-segment">
...
</div>
</div>
<ChannelMessages channelName={this.state.channelName} />
</div>
</div>
);
}
ChannelMessages.js
export default class ChannelMessages extends React.Component {
constructor(props) {
super(props);
this.state = {
channelName: this.props.channelName,
message: '',
messages: [],
textValue: ''
}
...
}
componentWillReceiveProps(nextProps) {
this.setState({channelName: nextProps.channelName})
}
componentDidMount() {
this.messageRef = firebase.database().ref('messages/' + this.state.channelName);
this.messageRef.limitToLast(500).on('value', (snapshot) => {
let messages = snapshot.val();
if (messages !== null) {
let newMessages = [];
for (let message in messages) {
newMessages.push({
author: {
displayName: messages[message].author.displayName,
photoURL: messages[message].author.photoURL,
uid: messages[message].author.uid
},
body: messages[message].body,
createdAt: messages[message].createdAt,
id: message
});
}
this.setState({ messages: newMessages, textValue: newMessages.body });
}
console.log(this.state.textValue)
});
}
componentWillUnmount() {
this.messageRef.off('value');
}
handleSubmitMessage(event) {
event.preventDefault();
let user = firebase.auth().currentUser;
this.messageRef.push().set({
author: {
displayName: user.displayName,
photoURL: user.photoURL,
uid: user.uid
},
body: this.state.message,
createdAt: firebase.database.ServerValue.TIMESTAMP
});
this.setState({ message: '' });
}
...
render() {
return (...);
}
}
why are you not using the channelName directly from the props? you are using the componentDidMount event. It runs only once. If you want to run the firebase code whenever a new channel name is passed; extract the fetching logic function and run it in componentDidMount and componentDidUpate(check here if it's different from the previous one)
ComponentDidMount runs only once - more here
ComponentDidUpdate doesn't run on initial trigger - more here
export default class ChannelMessages extends React.Component {
constructor(props) {
super(props);
this.state = {
message: '',
messages: [],
textValue: ''
}
...
}
componentDidMount() {
const {channelName} = this.props;
fetchFromDb(channelName);
}
componentDidUpdate(prevProps) {
if (prevProps.channelName !== this.props.channelName) {
fetchFromDb(this.props.channelName);
}
}
componentWillUnmount() {
this.messageRef.off('value');
}
handleSubmitMessage(event) {
event.preventDefault();
let user = firebase.auth().currentUser;
this.messageRef.push().set({
author: {
displayName: user.displayName,
photoURL: user.photoURL,
uid: user.uid
},
body: this.state.message,
createdAt: firebase.database.ServerValue.TIMESTAMP
});
this.setState({ message: '' });
}
...
render() {
return (...);
}
}
Related
From the title itself. I am fairly new to react and would like to know
how would you update the already "passed" data from parent to child. I have an alert component that will display the error message depending on the data acquired after an Axios request.
Parent
..
this.state = {
formContact: {
fullname: '',
contact:'',
email: '',
message: ''
},
formAlert: { alertMessage: 'default'}
};
handleClick() {
let rm = this;
axios({
method: 'post',
url: 'submit',
data: {
form: this.state.formContact
}
})
.then(function (response) {
let data = response.data.data;
rm.setState({
formAlert: { alertMessage: 'test' }
});
}).catch(function (response) {
//handle error
console.log(response);
});
}
render() {
return (
<div className="row">
<Alert data={this.state.formAlert} />
</div>
);
}
}
Child
class Alert extends Component {
constructor(props) {
super(props);
console.log(props);
// Holds the form state and input boxes
this.state = {
formError: {
icon: '',
header: '',
message: '',
errorType: 'errormsg'
}
};
}
render() {
return (
<div className={'style-msg ' + this.state.formError.errorType}>
<div className="sb-msg"><i className="icon-thumbs-up"></i>
<strong>Well done!</strong>
{this.state.formError.message}
</div>
<button type="button" className="close" data-dismiss="alert" aria-hidden="true">×</button>
</div>
);
}
}
It seems I cannot update the formAlert.alertMessage to "test" and pass the new data "test" to the child.
Any help would greatly be appreciated. Thanks
As you have passed data to Alert component,
<Alert data={this.state.formAlert} />
But in Alert component, you have never used that data.
I think instead of this,
{this.state.formError.message}
you should use this,
{this.props.data.alertMessage}
Update
In order to set props to state do this,
formError: {
icon: '',
header: '',
message: props.data.alertMessage,
errorType: 'errormsg'
}
Now you can use,
{this.state.formError.message}
When data changes after first render your Alert component's state will not get new data, for this you need componentDidUpdate method,
componentDidUpdate(prevProps, prevState) {
if (prevProps.data.alertMessage !== this.props.data.alertMessage) {
let formError = {...this.state.formError};
formError.message = this.props.data.alertMessage
this.setState({formError},()=>console.log(this.state.formError.message))
}
}
Your Child Component should use the data props to show the alert.
class Alert extends Component {
constructor(props) {
super(props);
console.log(props);
// Holds the form state and input boxes
this.state = {
formError: {
icon: '',
header: '',
message: '',
errorType: 'errormsg'
}
};
}
render() {
return (
<div className={'style-msg ' + this.state.formError.errorType}>
<div className="sb-msg"><i className="icon-thumbs-up"></i>
<strong>Well done!</strong>
{this.props.data.alertMessage}
</div>
<button type="button" className="close" data-dismiss="alert" aria-hidden="true">×</button>
</div>
);
}
}
I am using Formik form with React. Whenever the user submits (handleSubmit), I put an option whether or not to discard the change or keep the change.
In my render,
<Formik
initialValues={this.state.experiment}
onSubmit={this.handleSubmit}
component={formikProps => (
<ExperimentForm {...formikProps} submitText="Save Changes" />
)}
/>
handleSubmit()
handleSubmit(formdata: any, actions: any) {
const data = processFormData(formdata);
let changes = this.detectChanges(this.state.experiment, data);
this.setState({ tempFormData: data });
// changed field exists
if (changes.length !== 0) {
this.setState({
isDialogOpen: true,
changedFields: changes,
});
} else {
actions.setSubmitting(false);
this.setState({
message: 'Nothing Changed',
});
}
}
keepChanges() and discardChanges()
keepChanges () {
const data = this.state.tempFormData
makeMutation(UpdateExperimentQuery, {
update: {
id: this.props.match.params.id,
data,
},
})
.then(responseData => {
console.log(responseData)
this.setState({ isDialogOpen: false });
this.props.history.push('/i/experiments');
})
.catch(err => {
this.setState({
message: 'Error Updating Experiment',
});
console.log(err);
});
}
discardChanges () {
this.setState({ isDialogOpen: false });
this.componentWillMount();
}
The keepChanges() successfully updates the data with the given field, but discardChanges just closes the dialog but does not reset the data to original value even though I try to call componentWillMount() which fetches and renders the original unchanged data in the DB.
How can I reset the fields when I choose to discard the changes?
Edit
discardChanges () {
this.formik.current.resetForm();
this.setState({ isDialogOpen: false });
this.componentWillMount();
}
//I get an error when I do React.createRef();
class EditExperiment extends Component<EditExperimentProps, EditState> {
constructor(props: EditExperimentProps) {
super(props);
this.formik = React.createRef();
this.state = {
experiment: null,
message: null,
changedFields: [],
isDialogOpen: false,
tempFormData: []
};
this.handleSubmit = this.handleSubmit.bind(this);
this.clearMessage = this.clearMessage.bind(this);
this.detectChanges = this.detectChanges.bind(this);
this.keepChanges = this.keepChanges.bind(this);
this.discardChanges = this.discardChanges.bind(this);
}
EDIT2
type EditExperimentProps = {
history: RouterHistory,
match: Match,
experiments: ExperimentsState,
refetch: () => void,
};
type EditState = {
experiment: ?Experiment,
message: ?string,
};
class EditExperiment extends Component<EditExperimentProps, EditState> {
constructor(props: EditExperimentProps) {
super(props);
this.formik = React.createRef();
this.state = {
experiment: null,
message: null,
changedFields: [],
isDialogOpen: false,
tempFormData: []
};
this.handleSubmit = this.handleSubmit.bind(this);
this.clearMessage = this.clearMessage.bind(this);
this.detectChanges = this.detectChanges.bind(this);
this.keepChanges = this.keepChanges.bind(this);
this.discardChanges = this.discardChanges.bind(this);
}
To reset the Formik you need to call resetForm - see an example here.
handleSubmit(formdata: any, actions: any) {
...
// changed field exists
if (changes.length !== 0) {
...
} else {
actions.setSubmitting(false);
actions.resetForm();
}
}
EDIT:
There is another way to get "actions" and call them wherever in component by using react refs:
constructor(props) {
super(props);
this.formik = React.createRef();
}
//somewhere in render
<Formik
ref={this.formik}
initialValues={this.state.experiment}
onSubmit={this.handleSubmit}
component={formikProps => (
<ExperimentForm {...formikProps} submitText="Save Changes" />
)}
/>
// now somewhere else in the same component ...
componentDidUpdate(prevProps) {
if(somethingHappend) {
if(this.formik.current) {
this.formik.current.resetForm();
}
}
}
You need to include the initial state when you want to use resetForm. Example:
this.formik.current.resetForm(this.initialState.experiment);
This means you need to save the initialState too:
constructor(props) {
super(props);
this.initialState = this.state;
}
I managed to add Item to the list but can't render it.
My App.js:
class App extends Component {
constructor(props) {
super(props);
this.state = {
recipes: [{
...sample data...
}]
}
}
createRecipe(recipe) {
this.state.recipes.push({
recipe
});
this.setState({ recipes: this.state.recipes });
}
render() {
...
export default App;
and my RecipeAdd:
export default class RecipeAdd extends Component {
constructor(props) {
super(props);
this.state = {
url: '',
title: '',
description: '',
error: ''
};
}
...event handlers...
onSubmit = (e) => {
e.preventDefault();
if (!this.state.url || !this.state.title || !this.state.description) {
this.setState(() => ({ error: 'Please provide url, title and description.'}));
} else {
this.setState(() => ({ error: ''}));
this.props.createRecipe({
url: this.state.url,
title: this.state.title,
description: this.state.description
});
}
}
render () {
return (
<div>
...form...
</div>
)
}
}
In React dev tools I see the recipe is added with 'recipe'. How should I change my createRecipe action to add new recipe properly? :
It looks like you're wrapping the recipe in an extra object. You can see in your screenshot that index 3 has an extra recipe property.
It should be more like this -- just .push the recipe object directly:
createRecipe(recipe) {
this.state.recipes.push(recipe);
this.setState({ recipes: this.state.recipes });
}
Even better would be to not mutate the state object directly, by using concat instead:
createRecipe(recipe) {
this.setState({
recipes: this.state.recipes.concat([recipe])
});
}
I have an array of 10 objects (Lets call them "Blogs") which contain title, description and image-URL properties. I need to wrap each of the properties in HTML tags and export them all so they all load on a webpage together.
With my current code, I am only getting 1 of the objects in the current state loading on the page. How do I get all the objects in the same state?
class NewBlogs extends React.Component {
constructor(props) {
this.state = {
title: [],
description: [],
image: [],
loading: true
};
}
componentDidMount() {
axios.get('/new-blogs').then(data => {
const blogs = data.data;
var component = this;
for(var i in blogs) {
component.setState({
title: blogs[i].title,
description: blogs[i].description,
image: blogs[i].image,
loading: false
});
}
})
.catch(function(error) {
console.log(error);
});
}
render() {
return (
<div>
<h2>New Blogs:</h2>
<h3>{this.state.title}</h3>
<em>{this.state.description}</em>
<img src={this.state.image}></img>
</div>
);
}
}
export default NewBlogs
I haven't run/test this but try something like this
The API call appears to return a list of objects. If so just set state once the xhr completes and set loading false once.
In the react render() is where you could iterate over your list. The easiest way to do that is with '.map()'. You then simply return react elements for each object in your list.
Also let's rename 'component' to 'list'
class NewBlogs extends React.Component {
constructor(props) {
this.state = {
list: [],
loading: true
};
}
componentDidMount() {
axios.get('/new-blogs').then(data => {
// const blogs = data.data;
// var component = this;
this.setState({list: data.data, loading: false })
// for(var i in blogs) {
// this.setState({
// title: blogs[i].title,
// description: blogs[i].description,
// image: blogs[i].image,
// loading: false
// });
// }
})
.catch(function(error) {
console.log(error);
});
}
render() {
return (
<div>
{this.state.list.map(e => (
<h2>New Blogs:</h2>
<h3>{e.title}</h3>
<em>{e.description}</em>
<img src={e.image}></img>
))}
</div>
);
}
}
export default NewBlogs
I am intending to get snapshot val from Firebase within my React component. I want to get the values based on init of the component and attach a listener for changes.
class ChatMessages extends Component {
constructor(props) {
super(props);
this.state = {
messages: [],
};
this.getMessages = this.getMessages.bind(this);
}
getMessages(event) {
const messagesRef = firebase.database().ref('messages');
messagesRef.on('value', function(snapshot) {
this.setState({ messages: snapshot.val() });
});
}
componentDidMount() {
this.getMessages();
}
render() {
return (
<div className="container">
<ul>
<li>Default Chat Message</li>
{ this.state.messages }
</ul>
</div>
);
}
}
This is because 'this' is losing its context. So that, 'this.setState' is being undefined. You can have a reference for the actual 'this' via a variable called 'that'.
class ChatMessages extends Component {
constructor(props) {
super(props);
this.state = {
messages: [],
};
this.getMessages = this.getMessages.bind(this);
}
getMessages(event) {
const messagesRef = firebase.database().ref('messages');
let that = this
messagesRef.on('value', function(snapshot) {
// here
that.setState({ messages: snapshot.val() });
});
}
componentDidMount() {
this.getMessages();
}
render() {
return (
<div className="container">
<ul>
<li>Default Chat Message</li>
{ this.state.messages }
</ul>
</div>
);
}
}
Or if possible, you can use arrow function, which keeps its context.
getMessages(event) {
const messagesRef = firebase.database().ref('messages');
// here
messagesRef.on('value', snapshot => {
// here
that.setState({ messages: snapshot.val() });
});
}