Where to Put Code that should run First ReactJs + Mobx State Tree - reactjs

I have some code that grabs the users ipAddres. I do this right now in my componentDidMount in my app.js
async componentDidMount() {
await eventTrackingStore.getIpAddress();
}
So I did it in my app.js as it is my root component and I only want to set this once. This works fine if the user starts from the home page and navigates through the site.
However some pages can be loaded directly(ie you type in the url in your browser and it goes straight to that page).
Since the react lifecycle starts with most immediate component, which calls a method that expects the ipAddress code to be set but it does not get set till it hits the app.js
Now I could put the above code in each method but that gets tedious. Is there some sort of method in reactjs, or mbox or mbox state tree that would fire first?

If you use mobx-state-tree and you have a global store, then that global store can make the API call in the afterCreate method
const AppModel = types.model({
ips: types.array(types.string)
}).actions(self => ({
afterCreate() {
flow(function*() {
const ips = yield eventTrackingStore.getIpAddress();
self.setIps(ips)
})()
},
setIps(ips: string[]) {
self.ips = ips
}
}))
OR
The same thing you can do in a wrapped react component that wrappes every page of your app.
class App extends React.Component {
componentDidMount() {
eventTrackingStore.getIpAddress().then(res => {
// set the ips into a store or any logic you want in order to pass them down to children
})
}
render() {
return this.props.children
}
}

I can think of two solutions:
You can use react context
Context provides a way to pass data through the component tree without having to pass props down manually at every level.
Use context to share the store between all components and if the data is not loaded, initialize loading right there in that nested component.
If the data is already there then just take it,
getIpAddress method should return a promise, so in case when data is already there it will be immediately resolved.

Related

How to pass class instances to react-router-dom navigate state?

I'm trying to pass a class instance, which has private members, through to a navigate call for react-router-dom, through its state key.
The class instance I'm trying to pass:
class Cart{
#contents;
add(itemName){
const existingEntry = this.#contents[itemName];
const oldCount = existingEntry?.count;
const newCount = oldCount+1;
this.#contents[itemName] = {name: itemName, count: newCount};
return this;
}
get contents(){
return JSON.parse(JSON.stringify(this.#contents))
}
}
Passing the instance to navigate:
function SomeComponent(){
// some react code...
const navigate = useNavigate();
const handleClick = () => {
const item = 'Bananas';
const cart = new Cart().add(item);
navigate('/someURL', { state: {cart} });
}
// some react code...
}
But when I access it from the consumer component using useLocation, it turns into an empty object. This means I can't access the contents of the class, since the recieved object is just a plain object, and has no getter functions, like the class instance I passed in.
function ConsumerComponent(){
//some react code...
const { state } = useLocation();
console.log(state.cart); // '{}'
//some react code...
}
How can I pass it to navigate, while getting back the same instance, instead of a shallow copied object?
EDIT 1
Here is a link to a codesandbox that demonstrates the issue. Strangely enough, the code works in the sandbox; and I get the class instance at the ConsumingComponent. But try downloading the sandbox locally and running it. The ConsumingComponent will only be able to access a plain object(as hypothesized by #Drew Reese) in the comments. I would be inclined to believe that
"only JSON/string serializable objects can be passed via route state"
but I can't wrap my head around this discrepancy in behaviour between the sandbox and the local instance. Any hypotheses, ideas or even conjecture is greatly appreciated.
TMI: I'm trying to implement a checkout fn which accepts a Cart object as a parameter, and navigates to the checkout page #'/checkout', while passing the cart inside the navigate route state. The reason I wish to do so, is because the checkout fn is intended to checkout single objects(similar to a Buy now button on amazon), and hence I don't really want to store the Cart in my global state management system, since its a single-use class instance.

Use redux connect function passing props.children as React element

I need a component that starts polling for data from an API as soon as it gets mounted and it stops when unmounted. The data must be available for a child component.
This is my current implementation skeleton
class External extends Component {
render() {
const ConnectedPoller = connect(/*cut*/)(Poller)
return <ConnectedPoller {...this.props}>
{this.props.children}
</ConnectedPoller>
}
}
class Poller extends Component {
componentDidMount() {
this.model.startPolling();
}
componentWillUnmount() {
this.model.stopPolling();
}
render() {
const children = React.Children.map(this.props.children, child => {
return React.cloneElement(child, {...this.props});
});
return children;
}
}
There are a few components that need these data, I can use my poller as their parent in this way
<External>
<ComponentRequiringData {...this.props}>
</External>
This is working, but I would like to merge External into Poller. The problem is that I cannot find a way to do this
const ConnectedPoller = connect(/*cut*/)(this.props.children)
The connect function complains when I pass props.children instead of a "real" react element. Any suggestion?
DISCLAIMER: I don't poll at an ancestor level because it's a heavy resource-consuming task for the backend and I need those data only in a few components that are used rarely and are never rendered together in the same page.
The only reason to use redux' connect function, is if you want to connect to the state manangement - either get the current state, or dispatch an action. Since you aren't doing any of these here, there is no reason to use connect. Also, while it might work, there is no reason to use connect inside a rendering function. This will recreate the commponent over and over again for no reason. I guess you are doing it because you want to pass the component with props, but connect can receive props from a parent element as a second argument.

converting react classes to functions with redux

I'm still new to react/redux, after getting something like this to function
User.js
class User extends React.Component {
componentWillMount() {
this.props.fetchUser(.....);
}
render() {
return (
<Profile />
)
}
export default connect(null, {fetchUser})(User);
Profile.js
class Profile extends React.Component {
render() {
const { user } = this.props
return (
<h1>{user.profile.name}</h1>
)
}
const mapStateToProps = state => ({
user: state.store.user
});
export default connect(mapStateToProps, {})(Profile)
actions.js
export const fetchUser = (.....) => dispatch => {
fetch()
.....
}
reducers.js
case FETCH_USER:
return {
...state,
user: action.payload.user
};
As I understand it, the User component calls an action (fetchUser) from connect on componentWillMount(). That action calls an api, gets the data and the reducer adds that to the store within the state. The Profile component can then use connect to map the data from fetchUser in the store and display that data.
After reading some tutorials including https://github.com/reactjs/redux/blob/master/docs/basics/UsageWithReact.md
It looks like things can be simplified a bit without using classes.
If I were to change the User and Profile components to a more functional way, how would I do it?
eg.
const User = () => {
return (
<Profile />
)
}
how do I dispatch the fetchUser action and how do I simulate it to be called with the flow of componentWillMount()?
or am I just over complicating things?
There is also a way to support lifecycle methods in functional components.
https://www.npmjs.com/package/react-pure-lifecycle
import React from 'react';
import lifecycle from 'react-pure-lifecycle';
// create your lifecycle methods
const componentDidMount = (props) => {
console.log('I mounted! Here are my props: ', props);
};
// make them properties on a standard object
const methods = {
componentDidMount
};
const FunctionalComponent = ({children}) => {
return (
<div>
{children}
</div>
);
};
// decorate the component
export default lifecycle(methods)(FunctionalComponent);
I think you should keep using statefull components with redux...
https://medium.com/#antonkorzunov/2-things-about-purecomponent-you-probable-should-know-b04844a90d4
Redux connect — is a PureComponent.
Yes — a very important thing, a HoC for a molecule is a pure one. And works even inside other pure components. And gets store from a current context.
Same is working, for example, for styled-component — you can wrap it with PureComponent, but it will still react to Theme changes.
Solution is simple — bypass logic, use old school events bus, subcribe, wait and emit events.
Styled-componets:
componentWillMount() {
// subscribe to the event emitter. This
// is necessary due to pure components blocking
// context updates, this circumvents
// that by updating when an event is emitted.
const subscribe = this.context[CHANNEL];
this.unsubscribe = subscribe(nextTheme => { <----- MAGIC
React-redux:
trySubscribe() {
if (shouldSubscribe && !this.unsubscribe) {
this.unsubscribe =
this.store.subscribe(this.handleChange); <----- MAGIC
}
}
componentDidMount() {
this.trySubscribe();
}
Thus, even if parent Pure Component will block any update enables you to catch a change, store update, context variable change, or everything else.
So — something inside pure components is very soiled and absolutely impure. It is driven by side effects!
But this bypass straight logic flow, and works just differently from the rest of application.
So — just be careful. And don’t forget about magic.
Aaaand….
And this is a reason, why any redux store update will cause redraw in each connected component, and why you should use reselect just next to connect HoC —
to stop unnecessary change propagation.
But you should read this from another point of view:
redux-connect is a source of a change propagation.
redux connect is the end of a change propagation. It is still PureComponent.
And this leads to quite handy thing — you can control change propagation with redux-connect only. Just create a boundaries for a change. Lets talk about this in another article.
Conclusion
Pure components keep your application fast. Sometimes — more predictable, but often — less predictable, as long they change the way application works.
Stateless components are not pure, and may run slower than PureComponents by any kind.
But… if you very wish to create a fast application with good user experience — you have to use Pure Component.
No choice. But, now — you know hidden truth, and knew some magic…
React recommends that ajax request be made in componentDidMount(), rather than in componentWillMount(). For more info on this, read this post.
Since you want to make ajax requests in componentDidMount(), you need a class. There are two ways of writing component definitions: functional component and the class component. Functional components are more concise, but you don't get component lifecycle methods like componentDidMount(). Think of it as just a render function that takes props as inputs and outputs DOMs (in JSX). To override those lifecycle methods, you need to define them as a class.
If you want to use Redux, and want to make ajax requests in a Redux action, you should import the action creator function (fetchUser(..) in your case) that makes the ajax request, and dispatch(fetchUser(..)) in componentDidMount(). connect(..)ed components get dispatch(..) function passed to it by Redux store.
If you want to see how it's done in other redux apps, see the official example apps in the redux.js repo, paying attention to actions and containers: https://github.com/reactjs/redux/tree/master/examples
In Your case you can continue with statefull components no wrong in that
,If you need to go with functional way
There is a work arround
https://github.com/mobxjs/mobx/issues/162
Suggestion
Calling the api in componentDidMount will make sense than
componentWillMount , Because you can show the user something is
fetching.
I think,User component is designed nicely.It will act as a container for Profile to provide the Data.
Instead of making Profile component class oriented,it should be Stateless.
Lets User component pass the required data for Profile component.
You don't need to connect Profile component using redux-connect.Just render it as a Child component of User.
Profile
const Profile = (props) => {
const {user, likeProfile} = props;
//likeProfile()//call like this using dom event or programmatically.
return (
<h1>{user.profile.name}</h1>
)
}
You need to make some changes in User component.
Get the state for Profile component via mapStateToProps.
class User extends React.Component {
componentWillMount() {
this.props.fetchUser(.....);
}
render() {
const {user, likeProfile} = this.props;
return (
<Profile user= {user} likeProfile={likeProfile} /> //passed the user data to Profile component vua User
)
}
Map the user state for Profile in User connect.
const mapStateToProps = (state)=>{
return{
user : state.somereducerkey.user //this will be accessible in Profile via props { user}
}
}
export default connect(mapStateToProps, {fetchUser, likeProfile})(User);

React one time API call for multiple routes design

I am new to React and trying to implement an application. Basically
my application have several routes. Each
route is backed by the same set of back end data +some api calls
specific to route taking back end data attributes as api params.
So I wrote a Higher order component to call the
API to retrieve the back end data,store the state in redux store and
pass it as props to the wrapped component which works fine.
const withData = (WrappedComponent) => {
class DataWrapper extends Component {
constructor() {
this.state = {
c: {},
d: []
};
}
componentDidMount(){
this.props.fetchData();
}
componentWillReceiveProps(nextProps){
this.setState({
c: nextProps.data.CSubset,
d: nextProps.data.DSubset
});
}
render() {
return <WrappedComponent {...this.props} {...this.state}/>;
}
const mapStateToProps=(state)=>({
data:state.appData
});
return connect(mapStateToProps,{fetchData})(DataWrapper);
}
export default withData;
class AppComponent extends Component{
componentDidMount(){
this.props.fetchComponentSpecificData(c.dataAttribute);
}
render(){
return <div />;
}
}
export default connect(null,{fetchComponentSpecificData}(withData(AppComponent);
But the issue is API gets called for all routes.It should be one
time per full application flow.
The component specific data fetch happens before the common back end data is available causing the component specific API call to fail.
User can type in the URL and launch
into any route within application and the API has to be called only
once and the HOC has to systematically route to the correct route
based on data.
Please advise on the design approach
I would say that the most "Reacty" way of doing this would be to implement the global API calls in the componentWillMount method of the top-level component (say, AppComponent). Right now, you have put it in a component that will be mounted for each subcomponent of your app, and it might be tricky to prevent the API call from being fired every time it mounts.
Using a HOC to provide those data to other components of your app is not a bad idea, but it makes your app a bit more implicit, and I don't think you're gaining a lot : you're adding a component with implicit behaviour instead of just adding a line in mapStateToProps.
Firing page-specific API calls after the global API call has succeeded is quite tricky. You're going to need a way to monitor the fact that the global API call has resolved, and in React/Redux way of thinking, this means dispatching an action. To dispatch actions asynchronously, you're going to need a Redux middleware such as redux-thunk or redux-saga (I believe redux-thunk is a lot easier for beginners). Now, if you have a way to know whether or not the global API call is a success, you can wait for a specific action to be dispatched (say, GLOBAL_API_CALL_SUCCESS). Now, this is the part where I'm doing myself a bit of publicity : I've written redux-waitfor-middleware that allows you to wait for a specific action to be dispatched. If you used it, it might look like this :
export async function fetchComponentSpecificData() {
await waitForMiddleware.waitFor([GLOBAL_API_CALL_SUCCESS]);
// perform actual API call for this specific component here
}
I'm not saying that waitFor middleware is the best tool to achieve this, but it's probably the easiest to understand if you're beginning!

Redux dispatch before rendering

I want to dispatch an action before the component is rendered.
But the action is an async action integrated with redux-saga.
I have to know when is the async action is done, if it is done, then render the component.
To make this work, I have a unique id for each container and after the action done, the attribute { loaded: true } would be saved into store.
I am thinking of this way
#preload('uniqueId', (dispatch) => new Promise((resolve, reject) => {
dispatch(MyAction(resolve, reject));
})
#connect(....)
class MyComponent extends React.Component {
....
}
#preload is a function trigger the specified action in componenWillMount (For server side) or componenDidMount (For client side) and when the action call resolve(), the state.preloadState.uniqueId.loaded will set to true. It also wrap the component so that only render the component when state.preloadState.uniqueId.loaded === true.
#connect connect the data I wanna preloaded into redux store in the specified action.
I wonder if it is common practice to do data preload for redux, redux-saga app and also for server-side rendering (I have used redux-async-connect before, but I wanna make all nested component able to do the data preload so I bind to componentWillMount instead of some static function).
Yes you can't really stop a component from rendering (without having its parent simply not render it), but you can conditionally render nothing. Something like:
render() {
if (!state.data) { return null; }
return <div>{state.data}</div>
}

Resources