Paul Paul - 6 months ago 27
Javascript Question

React: Reload logic on route change

I currently have four routes in place using the same controller:



<Route
component={App}
path='/'
>
<Route
component={Search}
path='/accommodation'
/>
<Route
component={Search}
path='/accommodation/:state'
/>
<Route
component={Search}
path='/accommodation/:state/:region'
/>
<Route
component={Search}
path='/accommodation/:state/:region/:area'
/>
</Route>





The component connects the
mapStateToProps
to a function that loads data from an api.



// ACTIONS
// ==============================================

function mapStateToProps ({destination, properties}) {
return {destination, properties};
}





// CONNECT & EXPORT
// ==============================================

export default connect(mapStateToProps)(
connectDataFetchers(Search, [loadSearch])
);





and renders a list of results.

When the route is changed to any of the others using the same controller, the data is not reloaded with a relevant call to the api to fetch the new set of results.

Is this possible to do either with react-router of any of the componentWill functions?

SOLUTION



Thanks to @john-ruddell the following solution works:



componentWillReceiveProps = (nextProps) => {
if (this.props.params != nextProps.params) {
loadSearch(nextProps.params);
}
}




Answer

You need to add logic to request the data and your store needs to capture that and pass it down to the component

componentWillReceiveProps(nextProps){
    //boolean to check if the props.params have changed
        //fetch data request
}

Your store needs to update with the new data that is returned. this data should be passed down to this same component as props to be rendered.

You can also update your routes to simplify it a ton

<Route component={App} path='/'>
    <Route path='/accommodation(/:state)(/:region)(/:area)' component={Search} />
</Route>

Note, the parenthesis () specify an optional parameter. so instead of four routes for the same component you can have only one that works in all four states :)

Comments