reflux / refluxjs

A simple library for uni-directional dataflow application architecture with React extensions inspired by Flux
BSD 3-Clause "New" or "Revised" License
5.36k stars 330 forks source link

Does not call the action #510

Closed jonattanva closed 7 years ago

jonattanva commented 7 years ago

Hi, I have the following

Action

export default Reflux.createActions([ 'list']);

Store

export default class ProjectStore extends Reflux.Store {

    state = {
        projects : [],
        loading : false
    }

    constructor() {
        super();
        this.listenToMany(Actions)
    }

    onList() {
        //... request http
            this.setState({
                projects : success.body,
                loading : false
             });    
      }
}

Component

class Dashboard extends Reflux.Component {

    constructor(props) {
        super(props);
        this.store = ProjectStore;
        ProjectAction.list(); // >_<
    }

    render() {
        return (
            <div>
                {
                    this.state.projects.map((project, key) => {
                        return (
                            <div key={key}>{project.name}</div>
                        )
                    })
                }
            </div>
        );
    }
}

In version 5.0.4 it works correctly and in the last version 6.1.0 does not work.

BryanGrezeszak commented 7 years ago

The only reason that worked in the first place was because the actions were async by default. So the action wasn't actually calling the action in the constructor, it was waiting and doing it later (on the event loop, to be specific, which happened to call it after the mounting of the component and therefore the creation of the store).

In v6 actions are sync by default (except for ones with child actions). They call immediately. And in the constructor there's not been any store actually created yet.

First actions should probably be called on componentDidMount.

Or you could also manually make sure your store is created from the get-go by calling Reflux.initStore(ProjectStore) right after your store class.

Or you could simply make your action async (while defining it) or call it async (with ProjectAction.list.triggerAsync(); at call time), though I think the two former options are better practice.

jonattanva commented 7 years ago

Thank you!