GithubHelp home page GithubHelp logo

Comments (17)

gaearon avatar gaearon commented on April 27, 2024

@prepare(props => action) where action may be async action?

from react-redux.

gaearon avatar gaearon commented on April 27, 2024

I'm not sure you'd really need boundActions there. If you give it an action creator, the HOC can take care of dispatching itself.

from react-redux.

dzannotti avatar dzannotti commented on April 27, 2024

Uhm.... I think you need bound actions there because you might want to call multiple (async or not) actions. example

(props, boundActions) => { 
  boundActions.getUserProfile(props.userId);
  boundActions.resetFormX()
}

How can the HoC do this with unbound actions?
I'm not 100% sure if this would add confusion/fuel bad practices among newcomers, but i think that most people would have to use lifecycle events to achieve this, so why not facilitate it into the connector itself, other flux framework offer routeActions (which are pretty much this) and it's a common enough topic of questioning on slack

from react-redux.

dzannotti avatar dzannotti commented on April 27, 2024

This also could possibly facilitate the promise collection needed for server side initial rendering

from react-redux.

gaearon avatar gaearon commented on April 27, 2024

I'd like to see this as a separate package in userland first. When its API is nailed, we can consider including it.

from react-redux.

volkanunsal avatar volkanunsal commented on April 27, 2024

@dzannotti Is it possible to call an action from within another action right now? If it were possible, this might be better done from an action.

This also reminds me of Cerebral's signals, which stack up actions.

from react-redux.

gaearon avatar gaearon commented on April 27, 2024

Yes, you can do this with redux-thunk or similar middleware.

// assuming redux-thunk
function prepareComponent(props) {
  return function (dispatch) {
    dispatch(getUserProfile(props.userId));
    dispatch(resetFormX());
  }
}

@prepare(prepareComponent) 
...

The only problem is we want to only do this when specific prop changes.

from react-redux.

dzannotti avatar dzannotti commented on April 27, 2024

Interesting, I didn't think about that, recalling it on props change should be trivial, knowing if it's needed or not might not be

from react-redux.

gaearon avatar gaearon commented on April 27, 2024

That's why I'm not sure there's a general nice solution here. Different projects may solve this differently.

from react-redux.

gaearon avatar gaearon commented on April 27, 2024

Interesting pattern: passing custom function instead of action creator as second parameter:

import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { fetchUser, fetchRepos } from '../actions';
import User from '../components/User';

class UserPage extends Component {
  componentWillMount() {
    this.props.fetchData(this.props.userLogin);
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.userLogin !== this.props.userLogin) {
      this.props.fetchData(nextProps.userLogin);
    }
  }

  render() {
    const { user } = this.props;
    if (!user) {
      return <h1>Loading...</h1>;
    }

    return (
      <div>
        <User {...user} />
      </div>
    );
  }
}

UserPage.propTypes = {
  user: PropTypes.object,
  userLogin: PropTypes.string.isRequired,
  fetchData: PropTypes.func.isRequired
};

function mapStateToProps(state) {
  return {
    users: state.database.users
  };
}

function mergeProps(stateProps, dispatchProps, ownProps) {
  const { users } = stateProps;
  const { userLogin } = ownProps.params;

  return Object.assign({}, dispatchProps, {
    user: users[userLogin],
    userLogin
  });
}

function fetchData(userLogin) {
  return dispatch => Promise.all([
    dispatch(fetchUser(userLogin)),
    dispatch(fetchRepos(userLogin))
  ]);
}

export default connect(
  mapStateToProps,
  { fetchData },
  mergeProps
)(UserPage);

from react-redux.

dzannotti avatar dzannotti commented on April 27, 2024

That's pretty much the pattern i was looking for, but i need bind action + fetchData

from react-redux.

gaearon avatar gaearon commented on April 27, 2024

Why do you need it to be bound there?

function fetchData(userLogin) {
  return dispatch => {
    return Promise.all([
      dispatch(fetchUser(userLogin)),
      dispatch(fetchRepos(userLogin))
    ]).then(() => dispatch(resetForm());
  };
}

from react-redux.

dzannotti avatar dzannotti commented on April 27, 2024

Oh no, i don't, i just need boundActions to be passed down to the component, that's all

from react-redux.

dzannotti avatar dzannotti commented on April 27, 2024

Yeah re-reading the pattern is slightly off from what i normally use/need.

connect((state) => mereStateToProps, actionCreators, (props, dispatch) => {
// execute this on mount/props change
dispatch(fetchData());
})(MyComponent);

this would allow MyComponent to remain pure while still having route based actions

from react-redux.

malte-wessel avatar malte-wessel commented on April 27, 2024

Take a look at this (decorator) function. https://github.com/broucz/threads-redux/blob/master/client/decorators/onUpdate.js

The callback is only invoked if certain parameters change.

from react-redux.

gaearon avatar gaearon commented on April 27, 2024

While I'm happy to see this in userland, I don't think it belongs in react-redux.

from react-redux.

gaearon avatar gaearon commented on April 27, 2024

Here's another example of such HOC from redux-react-router-async-example:

import React, { PropTypes } from 'react'
import shallowEqual from 'react-redux/lib/utils/shallowEqual'

function mapParams (paramKeys, params) {
  return paramKeys.reduce((acc, key) => {
    return Object.assign({}, acc, { [key]: params[key] })
  }, {})
}

export default function fetchOnUpdate (paramKeys, fn) {

  return DecoratedComponent =>
  class FetchOnUpdateDecorator extends React.Component {

    static propTypes = {
      actions: PropTypes.object
    }

    componentWillMount () {
      fn(mapParams(paramKeys, this.props.params), this.props.actions)
    }

    componentDidUpdate (prevProps) {
      const params = mapParams(paramKeys, this.props.params)
      const prevParams = mapParams(paramKeys, prevProps.params)

      if (!shallowEqual(params, prevParams))
        fn(params, this.props.actions)
    }

    render () {
      return (
        <DecoratedComponent {...this.props} />
      )
    }
  }
}

Usage example:

@fetchOnUpdate([ 'username', 'repo' ], (params, actions) => {
  const { username, repo } = params
  actions.fetchRepo({ username, repo })
  actions.fetchRepoStargazers({ username, repo })
})
export default class Repo extends React.Component {
  ...
}

from react-redux.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.