Reputation: 7459
I am using react-router
v4 to generate dynamic routes which are loaded from an asynchronous API. The data retrieved from the API is passed through a function which will create the React routes, something similar to:
import Home from "containers/home"
import FeaturePage from "containers/featurePage"
response.map((item) => {
if (item.value.toLowerCase() === "home") {
return {
path: item.path,
component: Home,
exact: item.isExact
}
} else if (item.value.toLowerCase() === "featurePage") {
return {
path: item.path,
component: FeaturePage,
exact: item.isExact
}
} else {
// ...etc
}
});
Once the routes are loaded, they are added to the Redux store using an action-reducer as usual. This works well as the redux store supports functions.
However storing functions in the Redux store doesn't seem to be the best way forward. What would be a better implementation? I need to store the component which needs to be rendered, which is not serialisable.
Upvotes: 3
Views: 910
Reputation: 860
Just store the component name as strings? (Not sure why you wanna add them to the store though)
You can probably use them later like this:
import Home from "containers/home"
import FeaturePage from "containers/featurePage"
// Assume the routes have been added to the redux store
const Routes = {
Home,
FeaturePage
};
response.map(({ component, path, exact }) => {
return (
<Route
key={ path }
exact={ exact }
path={ path }
component={ Routes[component] }
/>
);
});
Upvotes: 1
Reputation: 5243
A React component is made up of the state of the component (made up of state
and props
) and some behavior (like functions and html markup) which is modified based on the state. Once you have created the component, the behavior of the component will not change; only the state of the component will change.
I would think saving the state of the component would be enough to recreate the component at a later time and you would not need to save the component in Redux; instead save the state of the component in Redux.
Regarding saving your Routes in Redux, the same applies; you should save the state of the Route rather than the route itself in your Redux store. You can have a function which could take this state object (containing the path, isExact, component name etc.) and convert it to a real component for you.
Hope this helps!
Upvotes: 0