When the user clicks in a link, React Router will display a component. The data this component will show came from an endpoint, so I'm wondering what's the best practice.
I've created a function called fetchData which uses fetch to perform a GET in an endpoint and then returns a promise. Once this promise is resolved, I would like to dispatch a Redux action to update the state.
I managed to do this with redux-thunk, but I would like to implement this without adding more libraries.
I'm trying to follow the 'container/presentational' idea and I'm using stateless functional components in React.
In a general overview, this is what I'm doing:
index.js
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
app.js
const App = () => (
<div>
<BrowserRouter>
<div>
<Header />
<Switch>
<Route exact path="/" component={Main} />
<Route exact path="/data-list" component={DataListContainer} />
</Switch>
</div>
</BrowserRouter>
</div>
)
dataListContainer.js
const mapStateToProps = (state) => {
return { data: state.data }
}
const mapDispatchToProps = (dispatch) => {
return { }
}
const DataListContainer = connect(
mapStateToProps,
mapDispatchToProps
)(DataList)
dataList.js
const DataList = (props) => {
const rows = props.data.map(data => {
return <Data data={data} />
})
return (
<div>
{rows}
</div>
)
}
And the Data component simply displays the data. I'm wondering where I should add the call to the function fetchData and where I should solve the returned promise. I imagine I will need to dispatch an action after the promise is resolved, but not sure where is the best place to do this.
Other question is: I would like to fetch the data only once, I mean, only when the user clicks the /data-list link. If it comes back to main page and then goes again to data-list, I would like to not call the endpoint again. Is there any call once feature hidden in React Route implementation?