What is the proper way to initialize data (asynchronously) with RefluxJS? Is there something similar to AngularJS' resolves, or the Flux implementation has nothing to do with this (The router should be handling this reponsibility)?
Proper way to initialize data [duplicate]
Asked Answered
In your application's top-level component, use the comoponentWillMount
method (docs) to trigger an action that fetches the data. This method will get called when the component is initially rendered.
For example:
// Create an async action, that will request data using a promise
// Using the recently released (v0.2.2) helpers for async actions
var actions = Reflux.createActions({
init: {asyncResult: true}
});
actions.init.listenAndPromise(promiseToGetData);
// Update the store when the init action's promise is completed
var store = Reflux.createStore({
listenables: actions,
onInitCompleted: function (data) {
// do stuff
this.trigger(data)
}
});
var App = React.createClass({
mixins: [Reflux.connect(store)],
componentWillMount: function () {
// When this component is loaded, fetch initial data
actions.init()
}
});
Just a question: If I am using refluxjs with react-router, what happens if the promise was rejected; Is the mounting halted (technically, nothing happens) or is it handled manually? –
Werbel
The component will still mount, the call to the action is fire and forget. If the promise is rejected, the store will still receive the result and you can add a
onInitFailed
handler. See github.com/spoike/refluxjs#asynchronous-actions for more about the async actions. –
Sarco Thanks. By the way, do you refer to
componentWillMount
rather than onComponentWillMount
? –
Werbel oops, sorry it's
componentWillMount
, I'll fix the answer –
Sarco There are at least a couple of problems with this code snippet which threw me off for a while.Firstly,
componentWillMount
expects a function. Also, should actions.load.listen...
be actions.init
? –
Affirmatory @AlexYork you are right, I wrote this quite hastily. –
Sarco
This is incorrect. It doesn't use the API that Reflux has out of the box. See my answer below. –
Cronus
No, it's not incorrect. This is the way recommended by React's documentation. You should not be making async requests in
getInitialState
. –
Sarco Reflux has an API for this actually.
The docs are poor at describing it, but Spoike (Reflux's author) gave an answer along with a code example:
https://mcmap.net/q/870273/-react-flux-getting-initial-state-into-a-store
This question was about fetching data asynchronously. Reflux sets the store's
getInitialState
method on the React components and should not be used for fetching data asynchronously. The example in the answer you linked to is for static values. See the official React documentation for an example and stackoverflow.com/questions/26615307 –
Sarco © 2022 - 2024 — McMap. All rights reserved.