Fetching data from server in Container and passing it to Component - reactjs

I've been learning React for the past few weeks and I'm struggling with a way to fetch a collection of data from server and presenting it using Redux.
What I have:
I have a <MoviesList /> component which renders a list of <Movie /> components inside it.
What i need:
I need to fetch these movies from a server and store it in my state.
What I'm struggling with:
If I create a container component, I'll use mapStateToProps to pass the movies from the state down to my <MoviesList /> component, but first I need to fetch it from the server, so I thought that I should do it in one of the container component's lifecycle hook, but then I'll have a movies prop (which should be validated with PropTypes) both in my <MoviesListContainer /> and <MoviesList />, which will force me to write a big prop validation in both components, which doesn't look right at all for me.
This wouldn't be a problem if I were to simply spread the props in the container using a function component, but since I need to fetch the movies in the lifecycle hook, it needs to be a class and I need to specify the props in both files.
So what would be the best way to achieve this?
Should I fetch these movies in a different place? Should I take a different approach for fetching it and avoiding these duplications? Or maybe I really should do the validation in both files?
Thanks everyone!

What I have done in the past is to have a function property which is called in the componentDidMount lifecycle event:
componentDidMount() {
this.props.onMount();
}
That property is mapped in the container using mapDispatchToProps to a thunk or some other async action (see the Async Actions documentation).
For a more sophisticated alternative see Redux First Router which allows to dispatch async actions from the router.

#JCE is right, you need to look into Async Actions. If you want to fetch the data and store it in Redux before passing it to your component, you must use a side-effect library (redux-thunks, redux-sagas, etc). The reason is that Redux actions are synchronous by nature and fetching an API is an asynchronous operation. The side-effects libraries will help you achieve that.

Related

How to dispatch action with result of apollo query?

In the root component, I have Apollo Query which retrieves data from the server then I want immediately dispatch this data to redux store and then use it in child's components on their first render.
So the scheme is like this :
<ApolloProvider>
<ReduxProvider>
<SomeChildComponent /> --- Can be a lot of nested components
</ReduxProvider>
</ApolloProvider>
Now I am using React.Context to pass data from Query to all child components and do other stuff with the local state by redux. But I need that query result to be in redux store.
So where would I place the dispatch method for this data?
I can't use componentDidMount because I need to handle this data in children before their first render. And also why I need componentDidMount for data which has already fetched and is ready to use.
I see the only way to dispatch it in the render method but I understand that is antipattern at all and can't find information about my case because every question are about fetching data via redux but I have it already so how to deal with this?
You can pass a function to the onCompleted property of the query component, it receives the result data as the first argument. From there you can dispatch your action.

Making API Calls with React for fetch data and render it

I am new to React and want to understand the difference from classic MVC.
I want to create a simple components that loads some data initially and renders let say a grid.
On some state or prop change it will reload the data and re-render.
What is the best approach in react from below two options?
using the lifecycle events to load the data, update some state and render while in another event will show some loading opacity.
Work with redux and react-redux? but in all example I cant see API calls.
Is this the role of a middleware (Thunk?)?
Will appropriate an explanation.
Both the approaches are correct. It depends on your use case. If you can avoid using redux in your app, use the lifecycle methods to make API calls (also called subscriptions in react documentation). If you think your app has many components and different components needs to share a state, then use redux.
You should also look at React hooks https://reactjs.org/docs/hooks-reference.html
You can use Effect Hook https://reactjs.org/docs/hooks-effect.html to make API calls and update your component's state.
Update:
Both Thunk and Sage are used to manage side effects in your application (making API calls from here). I've used saga, I don't know much about thunk.
How you would use redux-saga:
Say if you want to get some data for display on a button click, this is how it works:
On button click you dispatch an action, say GET_DATA
Your redux reducer will change some state on this particular action, say isLoading=true
You can use isLoading in your component to show a spinner/overlay
At the same time saga will listen to GET_DATA action and make the API call
If success, from Saga you'll dispatch an action, say GET_DATA_SUCCESS with the data from API call
Reducer will change isLoading=false and set the data in state, say apiData = { ... }
If failure, from Saga you'll dispatch an action, say GET_DATA_FAILED with the error code/message
Reducer will change isLoading=false and set the error in state, say apiError = { ... }
You can now use isLoading=false in you component to remove spinner and display the data (apiData) or error (apiError) in you component.
You can go through this tutorial to learn more https://redux-saga.js.org/docs/introduction/BeginnerTutorial.html

Redux - Set state by depending actions

I want to achieve the follow sequence of my data flow:
Get the record-id of react-router
Set this id as state property
If this property is set, all other dependent components, with it's own reducer and actions should get their data depending on the id
componentWillMount() {
this.props.actions.setItemId(this.props.params.id);
if(this.props.id){
this.props.fetchItemInformations(this.props.id);
}
}
I am aware that this flow won't work but I've no idea how to implement it.
Many ways to do this but if your problem is due to async issues then you can use middleware such as Redux Thunk. This will essentially allow you to chain your actions i.e. once the id is set then dispatch another action to do X.
See here - https://github.com/gaearon/redux-thunk
Alternatively, you could do your if statement within the componentWillReceiveProps () lifecycle event and check if it has been set there. If it has then dispatch your next action...
If I understand your question right, you want to fetch the property record-id from react-router (This is a url hash I assume?).
You can directly pass the this prop to all the children (as a prop) and handle the value in the children as you wish. To do this,
Pass the prop as well when rendering { this.props.children }; something like
{ React.cloneElement(this.props.children, { record-id: record-id }) }
This I'd say is the best practice; if you want to pass the record-id to other components (that are not direct children) of your parent component; you need to fire an action and handle the action to update relevant reducer states. Hope that helps.

proper react component usage

I have a project that uses React and Redux. I have multiple React components that need to use a common method that will scrape data out of the Redux Store, build a request object and fire off a rest request to the server.
I wouldn't want to write the method that does this more than one time. So, should this method be it's own React component, or should I just put it in a common javascript file? I'm not sure what the point of having a component would be if you're not rendering any JSX. On the other hand, if I put it in a common javascript file, is it possible to wire up redux to that file to get access to the states in the store?
Thanks in advance.
Adding the redux-thunk middleware lets you dispatch functions, which then get access to dispatch and getState(). From there you can do anything you want, such as using selector functions to extract pieces of state that you need, and making AJAX calls. The thunk action creators can be passed to components as props, including binding them to auto-dispatch:
function someThunk() {
return (dispatch, getState) => {
const state = getState();
// do anything you want here
}
}
const actions = {doStuffOnClick : someThunk};
export default connect(mapState, actions)(MyComponent);
Further resources:
redux-thunk is described in its repo at https://github.com/gaearon/redux-thunk .
I have a gist demonstrating some common thunk usage patterns at https://gist.github.com/markerikson/ea4d0a6ce56ee479fe8b356e099f857e.
My React/Redux links list has links to articles discussing thunks and side effects in the Redux Side Effects category.
It should not be a Component because, as you said, there is no visual aspect to it.
Create a new action that does just that and dispatch the action from anywhere you need. This action could check the store to see if the action has already happened and then do nothing (or refresh).
The module that uses import {createStore} from 'redux' creates your store. Import the created store in the action module and use store.getState() to inspect the current state of your store.

React props states and Redux

What is the different between states and props?
How can you pass a value of let's say CompomentA to ComponentB if we have have for example ComponentA which takes an input then ComponentB is suppose to output(to print it on the screen) that same value if we have a third component called CompomentContainer which is a container of both A and B?
What is Redux? the definition of redux on the main website does not make sense to me. How does it work exactly? How is it useful to react?
Please bear with me, I hope my questions make sense. Thank you.
Those are very valid questions. I've been there and I know how frustrating it is to read about redux and not understanding anything. For some reason people like to use fancy words, which sounds complicated but in reality things are very simple and easy.
What is Redux?
Redux is a Flux architecture. In simple words it will help you to manage the global state of your app.
How does it work exactly?
Redux will create a single "store", this store will have all the data that you need to render in your components, you can update the data using "actions", you will call the actions from your components, these actions will transfer the new data to the "reducers", inside of a reducer you will basically copy the data from the components to the global state (reducers should be pure functions).
How is it useful to react?
It's very useful! Mainly because you will be able to share data across components. Also by having a global state you could save it to the local storage (or a database) to add offline support.
What is the different between states and props?
You can define props to describe the properties that the component will receive when creating instances, you can think of props like parameters, for example:
<MyComponent name="Crysfel" lastname="Villa" />
The previous component is receiving two props, name and lastname. Props will allow you to send data from ComponentA to ComponentB, assuming ComponentB is a child of ComponentA. Props will also help you to receive data from redux. As a rule of thumb, you should never modify the value of the props, these values are just to receive data.
State on the other hand is an object that might contain configurations for your component, the idea is to handle the state of the component, for example a collapsible container, you could have a toggle property in the component's state and toggle the value when user clicks a button. However when using redux you will rarely use the component's state, because Redux is managing the state of your app.
For your second question about sending data between component, you would use redux for that, ComponentA should call an action and send the new data to the global state, then redux will update your component with the new data and then you can render the new data into ComponentB (using props).
What is the different between states and props?
State is data that is tied directly to the React component in which it is set. Props is data that is passed into a child component from the parent component. Unlike state, props are immutable and never "set" directly.
How can you pass a value of let's say CompomentA to ComponentB if we have have for example ComponentA which takes an input then ComponentB is suppose to output(to print it on the screen) that same value if we have a third component called CompomentContainer which is a container of both A and B?
To pass value from Component A to ComponentB you would provide the value as props, passed in via the ComponentA render function. Something like this:
class ComponentA extends React.component {
render() {
return <ComponentB myvalue={value} />
}
}
In ComponentB the value can be accessed: this.props.myvalue
What is Redux? the definition of redux on the main website does not make sense to me. How does it work exactly? How is it useful to react?
Redux is an implementation of the ideas of Flux with a few architectural differences. You can think of it as a library that helps you create a central data store that passes data one-way into React components. It allows you to maintain global state outside of the components themselves.
A top-level container component typically listens to the store and re-renders whenever the store data changes (see the connect function). The data is then passed from the container component into the children components that need that data so they can render properly.

Resources