wmik
wmik

Reputation: 784

React stateless functional components and component lifecycle

So I just switched to using stateless functional components in React with Redux and I was curious about component lifecycle. Initially I had this :

// actions.js

export function fetchUser() {
    return {
        type: 'FETCH_USER_FULFILLED',
        payload: {
            name: 'username',
            career: 'Programmer'
        }
    }
}

Then in the component I used a componentDidMount to fetch the data like so :

// component.js

...
componentDidMount() {
  this.props.fetchUser()
}
...

After switching to stateless functional components I now have a container with :

// statelessComponentContainer.js

...
const mapStateToProps = state => {
  return {
    user: fetchUser().payload
  }
}
...

As you can see, currently I am not fetching any data asynchronously. So my question is will this approach cause problems when I start fetching data asynchronously? And also is there a better approach?

I checked out this blog, where they say If your components need lifecycle methods, use ES6 classes. Any assistance will be appreciated.

Upvotes: 4

Views: 4514

Answers (2)

Michael Peyper
Michael Peyper

Reputation: 6944

Firstly, don't do what you are trying to to do in mapStateToProps. Redux follows a unidirectional data flow pattern, where by component dispatch action, which update state, which changes component. You should not expect your action to return the data, but rather expect the store to update with new data.

Following this approach, especially once you are fetching the data asynchronously, means you will have to cater for a state where your data has not loaded yet. There are plenty of questions and tutorials out there for that (even in another answer in this question), so I won't worry to put an example in here for you.

Secondly, wanting to fetch data asynchronously when a component mounts is a common use case. Wanting to write nice functional component is a common desire. Luckily, I have a library that allows you to do both: react-redux-lifecycle.

Now you can write:

import { onComponentDidMount } from 'react-redux-lifecycle'
import { fetchUser } from './actions'

const User = ({ user }) => {
   return // ...
}

cont mapStateToProps = (state) => ({
  user = state.user
})

export default connect(mapStateToProps)(onComponentDidMount(fetchUser)(User))

I have made a few assumptions about your component names and store structure, but I hope it is enough to get the idea across. I'm happy to clarify anything for you.

Disclaimer: I am the author of react-redux-lifecycle library.

Upvotes: 4

loelsonk
loelsonk

Reputation: 3598

Don't render any view if there is no data yet. Here is how you do this.

Approach of solving your problem is to return a promise from this.props.fetchUser(). You need to dispatch your action using react-thunk (See examples and information how to setup. It is easy!).

Your fetchUser action should look like this:

export function fetchUser() {
  return (dispatch, getState) => {
      return new Promise(resolve => {
          resolve(dispatch({         
          type: 'FETCH_USER_FULFILLED',
          payload: {
            name: 'username',
            career: 'Programmer'
          }
        }))
      });
  };
}

Then in your Component add to lifecycle method componentWillMount() following code:

componentDidMount() {
  this.props.fetchUser()
    .then(() => {
      this.setState({ isLoading: false });
    })
}

Of course your class constructor should have initial state isLoading set to true.

constructor(props) {
  super(props);

  // ...

  this.state({
    isLoading: true
  })
}

Finally in your render() method add a condition. If your request is not yet completed and we don't have data, print 'data is still loading...' otherwise show <UserProfile /> Component.

render() {
  const { isLoading } = this.state;

  return (
    <div>{ !isLoading ? <UserProfile /> : 'data is still loading...' }</div>
  )
}

Upvotes: 1

Related Questions