Hasan
Hasan

Reputation: 2552

Where to keep active user data on React + Redux client application

On my React + Redux client app, I need to get the active user info (fetch from myapp.com/users/me) and keep it somewhere so that I can access it from multiple components.

I guess window.activeUser = data would not be the best practice. But I could not find any resource about the best practice of doing that. What would be the best way to do what I want?

Upvotes: 3

Views: 3813

Answers (3)

Lyubomir
Lyubomir

Reputation: 20027

You can use React's context, HOC or global variables to make your data available to multiple components, via context

Something like...

class ParentDataComponent extends React.Component {
   // make data accessible for children
  getChildContext() {
    return { 
      data: "your-fetchet-data"  
    };
  }

  render() {
    return < Child />
  }
}

class Child extends React.Component {
  render() {
    // access data from Parent's context
    return (<div> {this.context.data} </div>); 
  }
}

Upvotes: 2

riley
riley

Reputation: 181

you can keep it in a separate reducer, and then import multiple parts of your state with connect() in your components.

Say if you have 2 reducers called users.js and tags.js which are combined with combineReducers when setting up your store. You would simply pull different parts by passing a function to your connect() call. So using es6 + decorators:

const mapStateToProps = state => {
  return {users: state.users, tags: state.tags}
}

@connect(mapStateToProps)
export default class MyComponent extends React.Component {

and then down in your render function:

return (
  <div>
    <p>{this.props.users.activeUsernameOrWhatever}</p>
    <p>{this.props.tags.activeTags.join('|')}</p>
  </div>
);

So your different reducer states become objects on this.props.

Upvotes: 6

Mani Shooshtari
Mani Shooshtari

Reputation: 780

create an action creator and call it on componentWillMount of the appropriate component so it runs right before your component mounts, and in the action creator fetch the data you need and pass it to a reducer. in that reducer you can keep the data you want throughout your application. so whenever you needed the data you can retrieve it from redux state. this tutorial from official redux website covers everything you need to know. mention me if you had any questions.

Upvotes: 1

Related Questions