I need to create an element that, when rendered, loads its own data and displays it. I wrote something like this:
export default class MyComponent extends React.Component {
constructor() {
super();
this.state = {
content: "Loading..."
};
}
render() {
Data.singleton().load(0, 100, "desc").then((function(data) {
this.setState({
content: {JSON.stringify(data, null, 3)}
});
}).bind(this));
return <pre>{this.state.content}</pre>
}
}
Now, this works but the react documentation clearly states that:
The render() function should be pure, meaning that it does not modify
component state
So I was wondering what's the best design pattern for this kind of needs.
p.s.: I know I could load the data in the containing element and pass it in to MyComponent using props. I am also aware that that seems "the way" to go with react but I was wondering if there are other legitimate ways.
Thanks
Here is an example: JSFiddle
This should be handled in componentDidMount (note, I'm using a setTimeout, to 'simulate' the async call):
class Main extends React.Component{
constructor(props){
super(props);
this.state = {
data: 'Loading...'
}
}
componentDidMount() {
console.log('Mounted');
setTimeout(() => {
this.setState({
data: 'set after waiting 2 seconds'
})
}, 2000)
}
//
render() {
return (
<div>{this.state.data}</div>
);
}
}
It looks like all you need to do is toss that function into componentDidMount or componentWillMount, like so:
componentDidMount() {
// state-altering logic
}
render() {
return <pre>{this.state.content}</pre>
}
https://facebook.github.io/react/docs/component-specs.html#mounting-componentwillmount
Since its recommended to have your ajax method in the componentDidMount
https://facebook.github.io/react/docs/component-specs.html#mounting-componentdidmount
You can structure your react component like this
export default class MyComponent extends React.Component {
constructor() {
super();
this.state = {
content: "Loading..."
};
}
componentDidMount(){
Data.singleton().load(0, 100, "desc").then((data)=> {
this.setState({
content: {JSON.stringify(data, null, 3)}
});
});
}
render() {
return <pre>{this.state.content}</pre>
}
}
Related
I have this code:
export default class FinancesPage extends React.Component {
constructor(props) {
super(props);
this.state = {users: []};
}
componentWillMount() {
firebase.database().ref('Users').orderByChild('transactions').startAt(1).on('value', snap => {
const users = arrayFromObject(snap.val());
this.setState({users: users});
});
}
render() {
return (
<div>
<NumberOfPurchasesComponent users={this.state.users}/>
</div>
)
}
}
And this code:
export default class NumberOfPurchasesComponent extends React.Component {
constructor(props) {
super(props);
this.state = {users: this.props.users};
}
componentWillMount() {
const users = this.state.users;
// Do stuff here
}
render() {
return (
{/*And render stuff here*/}
);
}
}
What's happening right now: The parent element FinancesPage passes an empty array of users to the child NumberOfPurchasesComponent. I need it to pass a new value of the array every time there is an update.
And i want to pass the users from FinancesPage to NumberOfPurchasesComponent, but users data is obtained async. How can I make the NumberOfPurchasesComponent refresh when the variable value is obtained?
Have you tried to use componentWillReceiveProps? I mean something like:
export default class NumberOfPurchasesComponent extends React.Component {
constructor(props) {
super(props);
this.state={users: []}
}
componentWillReceiveProps(nextProps) {
if(nextProps.users && nextProps.users!==this.state.users){
this.setState({
users: nextProps.users
})
}
}
render() {
return (
{/*And render stuff here*/}
);
}
}
This way the component knows when it has to re-render.
The FinancesPage implementation looks good. The problem lies in NumberOfPurchasesComponent in this particular piece of code :
constructor(props) {
super(props);
this.state = {users: this.props.users};
}
Am assuming in the render method of NumberOfPurchasesComponent you are using this.state.users instead of this.props.users.
constructor runs only once. Now as you mentioned data is fetched async, which means NumberOfPurchasesComponent is initially rendered even before the the response is obtained. Hence its constructor method which runs only once sets the users state to []. Even if the props gets updated from FinancesPage, as the render in NumberOfPurchasesComponent uses state, no re-render happens.
Try using this.props.users directly in NumberOfPurchasesComponent render and see if it works.
As per FinancesPage page it is well and good with codebase, but problem is why you are making setstate if there is no any manipulation of user's data as you got from API call.
So without making setState just pass it as direct
render() {
return (
<div>
<NumberOfPurchasesComponent users={this.props.users}/>
</div>
)
}
so whenever the API calls to fetch the response, here update value get in passed to NumberOfPurchasesComponent class.
this is the first time I face this warning message.
Can't call setState on a component that is not yet mounted.
Follows:
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 MyComponent component.
The "not yet mounted" part actually makes little to no sense as the only way to trigger the issue is to call a function by clicking a button from a component that needs to be mounted in order to see the button. The component is not unmounted at any given time neither.
This dummy component reproduces the error in my app:
import PropTypes from 'prop-types'
import React from 'react'
export default class MyComponent extends React.Component {
constructor (props) {
super(props)
this.state = {
initial: 'state'
}
this.clickMe = this.clickMe.bind(this)
}
clickMe () {
this.setState({
some: 'new state'
})
}
render () {
return (
<div>
<button onClick={this.clickMe}>click</button>
</div>
)
}
}
I am using:
"react": "16.3.2",
"react-dom": "16.3.2",
"mobx": "4.2.0",
"mobx-react": "5.1.2",
Did I miss something in the latest React/mobx version? (note the component does not use any mobx related stuff but its parent is a mobx-react observer)
Edit:
There must be something related to the component instance, further investigation has shown that in some cases, creating an handler inside the render function will make this warning disappear, but not in all cases.
class MyComponent extends React.component {
constructor (props) {
// ...
this.clickMeBound = this.clickMe.bind(this)
}
clickMe () {
...
}
render () {
// works
<button onClick={() => {this.clickMe()}}>click arrow in render</button>
// warning: Can't call setState on a component that is not yet mounted.
<button onClick={this.clickMeBound}>click bound</button>
}
}
Edit 2:
I have removed 'react-hot-loader/patch' from my entries in my Webpack config and some weird issues like this one have disappeared. I'm not putting this as an answer because the error message itself is still weird and this causes a warning in the console. Everything works fine though.
This warning that you are getting is because you are setting a reference to clickMe method in the constructor, which is then using the setState().
constructor (props) {
super(props)
this.state = {
initial: 'state',
some: ''
}
this.clickMe = this.clickMe.bind(this); <--- This method
}
clickMe () {
this.setState({
some: 'new state' <-- the setState reference that is causing the issue
})
}
Try removing the this.clickMe = this.clickMe.bind(this) from constructor and do it in a lifecycle method like componentWillMount() or ComponentDidMount(). For react 16 and above you can use the componentWillMount method with "SAFE_" prefix. [SAFE_componentWillMount]
componentWillMount() {
this.clickMe = this.clickMe.bind(this);
}
clickMe () {
this.setState({
some: 'new state'
})
}
You just need to use the componentDidMount() method. As the React documentation tells in the component life cycle, if you need to load data from a remote endpoint, this is a good place to instantiate the network request and you may call setState() immediately in componentDidMount().
Like this:
componentDidMount(){
this.clickMe = this.clickMe.bind(this);
}
clickMe () {
this.setState({
some: 'new state'
})
}
Just add following line to your
code
export default class MyComponent extends React.Component {
constructor (props) {
super(props)
this.state = {
initial: 'state',
some: '' // <------- THIS LINE
}
this.clickMe = this.clickMe.bind(this)
}
clickMe () {
this.setState({
some: 'new state'
})
}
render () {
return (
<div>
<button onClick={this.clickMe}>click</button>
</div>
);
}
}
You should not use setState in the constructor since the component is not mounted yet. In this case clickMe() method calls setState().
Instead, initialize the state directly. Like,
constructor(props) {
super(props);
// Don't call this.setState() here!
this.state = { counter: 0 };
this.handleClick = this.handleClick.bind(this);
}
example if from https://reactjs.org/docs/react-component.html#constructor
The setState() is used so that we can reflect the state changes by re-rendering. Since the component is not rendered yet we can change the state directly and changes will reflect on the call of the render() method.
As #Amida mentioned, hot-loader seems to be the issue. Whoever is using
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true,
ReactHotModuleReplacement = true
});
in Startup.cs, remove it and the issue will disappear. I don't know why, but this is my current workaround.
EDIT:
Update of "react-hot-loader" and "webpack-hot-middleware" to latest versions fixed the issue
If this error is happening in one of your tests, you might need to render the component to an element before accessing it (i.e. simply doing let app = new App; is not enough). Rendering will effectively mount the component and its children, as explained in this other answer and then you will be able to use the result object to perform operations without triggering the setState error. A simple App.test.js example:
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div); // <-- App component mounted here
// without JSX: ReactDOM.render(React.createElement(App), div)
ReactDOM.unmountComponentAtNode(div);
});
test('array length decreased after removal', () => {
const div = document.createElement('div');
let app = ReactDOM.render(<App />, div); // <-- App component mounted here
const origArrLen = app.state.arr.length;
app.removeAtIndex(0);
expect(app.state.arr.length).toEqual(origArrLen - 1);
ReactDOM.unmountComponentAtNode(div);
});
Where the App component could have:
class App extends Component {
state = {
arr: [1,2,3]
};
removeAtIndex = index => {
const { arr } = this.state;
this.setState({ arr: arr.filter((el, i) => i !== index) });
};
// render() { return ( ... ) }
}
You should assign the initial state in the constructor() . then call setState() immediately in componentDidMount(). to trigger an extra rendering, before the browser updates the screen. in this case render() method will be called twice and the user won’t see the intermediate state.
Your code will look like this :
import PropTypes from 'prop-types'
import React from 'react'
export default class MyComponent extends React.Component {
constructor (props) {
super(props)
this.state = {
initial: 'state' // initialize your state in the constructor()
}
}
componentDidMount(){
this.clickMe = this.clickMe.bind(this)
clickMe () { // call setState() in componentDidMount()
this.setState({
some: 'new state'
})
}
}
render () {
return (
<div>
<button onClick={this.clickMe}>click</button>
</div>
)
}
}
Imagine I have some "page" component, which needs to ask for data from a server. The data it requests will depend on whether or not the current user is authenticated. Further, in the event of a login, the page will want to reload the data. My question is, how can I accomplish something like this using HOCs rather than inheritance?
To illustrate the problem, I'll demonstrate a solution using inheritance. The program will have the following objects. I'll leave out the boilerplate code.
session: an EventEmitter that emits start when the session changes (either a login or a log out).
Page: the superclass that all pages inherit from
MyPage: the subclass of Page in this example
API: will be an API class for retrieving data from the server
Here's the code:
// Page superclass
class Page extends React.Component {
componentWillMount() {
session.on("start", this.loadData);
this.loadData();
}
loadData() {
// this method is overwritten in subclasses
}
}
// MyPage subclass
class MyPage extends Page {
loadData() {
if(session.isAuthenticated()) {
API.loadPrivateData();
} else {
API.loadPublicData();
}
}
}
Here's a solution that uses an HOC, but seems less elegant than inheritance. It still requires that every "subclass" page have a method loadData, and it requires that method to be called in every "subclass's" componentWillMount.
// Page HOC
function Page(WrappedComponent) {
return class EnhancedPage extends React.Component {
componentWillMount() {
session.on("start", this.loadData);
// this._page.loadData() will fail here
// since this._page is undefined until rendering finishes
}
loadData() {
this._page.loadData();
}
render() {
return <WrappedComponent {...props} ref={(e) => { this._page = e; }} />
}
}
}
// MyPage
class MyPage extends React.Component {
componentWillMount() {
this.loadData();
}
loadData() {
if(session.isAuthenticated()) {
API.loadPrivateData();
} else {
API.loadPublicData();
}
}
}
const component = Page(MyPage)
// what would make sense here is to have a method something like
// const component = Page(MyPage, () => MyPage.loadData())
// but then the MyPage.loadData logic would need to be defined
// elsewhere
This pattern will happen often: I'll want to load some data, then reload when the session changes. I'd like to understand the "react" way of accomplishing the same.
EDIT: I am not trying to pass a username or "loggedIn" flag through the HOC. That is to say something like <WrappedComponent isLoggedIn={session.isAuthenticated()} {...props} /> won't cut it here. Tying the API logic to props requires that I check for changes in MyPage.componentWillUpdate().
When using a HOC you shouldn't place the loadData function on the wrapped component. Instead pass the function as a parameter to the HOC constructor.
Something like this might work for you. The sessionHoc function takes a callback function which'll be called every time the session state changes. Its result will be passed to WrappedComponent as a data prop.
function sessionHoc(onSessionChange) {
return function (WrappedComponent) {
return class extends React.Component {
constructor(props) {
super(props);
this.state = {
data: null,
};
session.on('start', this.handleSessionChange.bind(this));
}
handleSessionChange() {
this.setState({
data: onSessionChange(),
});
}
render() {
return <WrappedComponent data={data} {...this.props} />
}
};
};
}
class MyPage extends React.Component {
render() {
// Just access this.props.data here!
}
}
const EnhancedPage = sessionHoc(function () {
if (session.isAuthenticated()) {
return API.loadPrivateData();
} else {
return API.loadPublicData();
}
})(MyPage);
Hopefully this helped! :)
I am using React v0.14.8. I tried to call the fetchData function from another component. Here is my code:
export default class TagUtils extends React.Component {
deleteTag = () => {
Tags.deleteTag(this.props.tag).then(function(response){
if(response.message === 'tag successfully deleted')
Sidebar.fetchData();
});
}
// other codes
And:
export default class Sidebar extends React.Component {
fetchData() {
Tags.getTags().done((response) => {
this.setState({tags: response.tags || [], loaded: true});
});
}
//other codes
When I called deleteTag, I got this error in my console:
TypeError: _SidebarJsx2.default.fetchData is not a function
You can't call Sidebar.fetchData because fetchData is not a static member of Sidebar, it is an instance member. This means you need an instance of Sidebar to call fetchData on, for example new Sidebar().fetchData(). Of course, this is not how a React component is supposed to be used, and it would not set state on all other Sidebar instances, so it wouldn't be meaningful.
What you want to do is pass a callback to your TagUtils component:
export default class TagUtils extends React.Component {
deleteTag = () => {
Tags.deleteTag(this.props.tag).then((response) => {
if(response.message === 'tag successfully deleted')
this.props.onDeleteTag();
});
}
}
export default class Sidebar extends React.Component {
fetchData() {
Tags.getTags().done((response) => {
this.setState({tags: response.tags || [], loaded: true});
});
}
render() {
return (
{ this.state.tags.map((tag) =>
<TagUtils tag={tag} onDeleteTag={this.fetchData} />) }
);
}
}
If you have to thread this callback through several layers of components that's okay, that's typical in React. However, if you find yourself passing a lot of stuff down props through many component layers that seem out of place, or trying to reconcile changes across large horizontal spaces in your app, this is a primary use-case for things like Flux and Redux.
From what I understand, HOCs in ReactJS add props to your decorated component, but I want to add methods that can also act on the state.
As an example, I generally never call this.setState() without checking this.isMounted() first. In essence, I want:
export default ComposedComponent => class BaseComponent extends React.Component {
static displayName = "BaseComponent";
constructor(props) {
super(props);
}
//------> I want this method to be available to any ComposedComponent
//------> And it has to act upon the state of ComposedComponent
updateState(obj) {
if (this.isMounted() && obj) {
this.setState(obj);
}
}
render() {
return (
<ComposedComponent {...this.props} {...this.state} />
)
}
}
Say I want to decorate my component Home. So I'd just return it as export default BaseComponent(Home).
But this.updateState() is not available inside Home class. How do I solve this?
Okay, I figured it out. I had spent too much time on this, so I hope this answer could help somebody out as well. Short answer: add the method in your decorator to props, then bind it in your decorated class' constructor.
Here is the code:
export default ComposedComponent => class BaseComponent extends React.Component {
static displayName = "BaseComponent";
constructor(props) {
super(props);
// Note how I am adding this to state
// This will be passed as a prop to your composed component
this.state = {
updateState: this.updateState
}
}
updateState(obj) {
this.setState(obj);
}
render() {
return (
<ComposedComponent {...this.props} {...this.state} />
)
}
}
And here is an example of a class that would use it (I'm using ES7 for simplicity):
#BaseComponent
class Home extends React.Component {
static displayeName = 'Home';
constructor(props) {
super(props);
// And here I am binding to it
this.updateState = this.props.updateState.bind(this);
}
render() {
return (
<div>Hi</div>
)
}
}