Different ways to fetch values from web services in react redux? - javascript

Trying to find the best way to fetch values from web services in ReactJs, redux.
Found ways using useEffects, fetch, redux-thunk, redux-saga.
But which is best to be used..?

This is a bad bad question. Okay, I cannot even explain why it's bad. I'll start with this, you're talking about completely different things.
I guess you're asking about how to make network requests in react. Here's brief description of the things you're talking about and why they are used:
useEffect: It's a hook in react, with which you can run an effect(basically running a function) on every or if depending on a state, some renders.
fetch: It is a web API with which you can make ajax requests(network requests) which is based on promises. Previously, we had XHR for doing so which is event-based. It is still used because fetch doesn't allow tracking the download progress of the response download. 'Should I use fetch or XHR for making requests', now that'd be a good question.
redux-thunk && redux-saga: Now you'd wanna use this with redux. In redux, as you probably know, dispatching action is synchronous. So if you wanna do some asynchronous task and dispatch the action object after that, then look into redux-thunk or redux-saga.
So the question shouldn't be 'Which of these should you use for fetching things off the web', because they're not specifically used for that purpose.

There are many differnt ways to doing that.
Basically useEffect is a hook and can not fetch any data directly.
Then you must pay attention to your app and select one that meet the needs of you. So there is no any best. If your application ia in a larg scale, i suggest react-query, then redux saga(if api reault is needed in some places)

Related

How to keep a React component in sync with backend?

I'm working on a small React application that uses Redux for state management.
The table below displays a dynamic list of objects, which are retrieved from the REST backend, which is implement in Java with Spring. Currently, I have to click a button in order to add the latest data delta (to the Redux store).
The table should update automatically in a performant way. I found a hacky workaround that recursively used Window's setTimeout method to periodically fetch data from the backend, but I did not like the solution.
What frameworks, tools, or approaches can I use for auto-updating that integrate well with React, Redux, React Redux, and Redux Thunk?
Since you're already using redux and react-redux, if an action is dispatched and the store's state is updated, the component should be rerendered with the new data.
When you call setTimeout to periodically fetch data, you're using a technique called polling.
To avoid the need to do polling, it's also up to the backend, whether you support WebSocket or GraphQL's subscription or using some kind of real-time datasource (e.g. Firebase)
May be CouchDB (or Couchbase (it's not the same) with PouchDB could help? I what try it in couple of days.
Seems they have Spring Data libraries
Using window.setInterval is better than window.setTimeout for this purpose. Other than fetching periodically data from your client, you could look into a websockets library such as socket.io although this will need configuration server-side.
If you are talking about auto-updating data reactively - when something in your database is updated - you need some kind of socket server for that. You can fire an event from your backend, and subscribe to it in your frontend, and then perform a query to fetch the data. I don't think using setInterval is a good idea for this type of stuff (in most cases).
Check out Pusher.

Why we need redux in react

I was done one small web application using ReactJS. It's easy to maintain and understandable. Now I learned Redux and plan to implement on it.
Its need some more stuff and extra things to do (To create store, Reducers etc.). I personally thought without redux the react is fine and easy to understand and maintain the states. Then why we need extra stuff (Redux)?
Reasons to use Redux:
Same piece of application state needs to be mapped to multiple
container components.
A good example of this is session state. When the app first loads, often information about the user needs to be shared with various components in the titlebar and each page. It’s likely these components don’t have any direct relationship so Redux provides a convenient way to share state.
Global strong textcomponents that can be accessed from anywhere.
It’s common to have components that live for the life of the application (for a single-page app this is every time the entry point is reloaded) that do things like show notifications, snackbars, tooltips, modals, interactive tutorials, etc. With Redux, you can create actions that dispatch commands to these components so, for example, if the code makes a asynchronous request to the backend it can dispatch a show snackbar action if the request fails. Without Redux, you would need some other event system or have to instantiate the snackbar component every time it gets used.
Too many props are being passed through multiple hierarchies of
components.
If a higher-level component is provided with a dozen props and uses only two of them, and the rest are passed down to a lower-level component, then consider refactoring with Redux. This scenario happens a lot with wrapper components that just provide layout styles, but don’t require a lot of data or configuration. It’s more practical to side-chain Redux directly into a lower-level component in this case.
State management using setState is bloating the component.
This is pretty subjective, but components that are over several hundred lines of code start to become harder to reason and maintain. Separating out the state management into a reducer breaks up the code and makes it more readable.
Caching page state.
When the user does some stuff to a page, then goes to another page and comes back, the expectation usually is to have the page in the same state. Some of this can be addressed by saving the page state in the backend and recalling it on page load. But, often things like search input values and expanded/collapsed accordions are just overkill to store in the backend. Since reducers typically initialize and live throughout the session, they can cache the page state so things remain the same.
Managing the state can be complex. Although react provides us with the state property but passing the state from component A to component B can be quite complex when the application grows. Here is a simple example which shows why do we need redux.
Consider an application with two functionalities "Users" and "Products".
Users have authentication implemented where they can sign-up and sign-in and the users can view the dashboard only when they are authenticated.
The other functionality "Products" also require user authentication information because the "Cart" operations will be accessible when the user is authenticated/signed-in. To get user authentication information at this part will require alot of state/props passing from "Users" component to a different section of the application "Products".
This is when Redux comes in picture, it provides a central store (stores entire application state) which is then available to the entire application.
TL;DR: Because you've done "one small web application". Not all web applications are small.
The most trivial examples of why you might need it include:
Sometimes unrelated components need to share state.
Sometimes state needs to be updated by things other than components.
Is it always necessary? Absolutely not. But breaking up state handling may confer advantages to non-small web applications, or complex interactions.
If all you have is a simple hierarchy of components, and things very low in that hierarchy never need to modify state that higher-level components need, then it brings in complexity that might not be necessary.
(Although even in those cases, it may be helpful; as always, "it depends".)
If you're building a house, you probably don't need a jackhammer even if you've learned how to use it.
You don't need Redux if your application's state is easy to manage without it.
As said in redux motivation page:
As the requirements for JavaScript single-page applications have
become increasingly complicated, our code must manage more state than
ever before. This state can include server responses and cached data,
as well as locally created data that has not yet been persisted to the
server. UI state is also increasing in complexity, as we need to
manage active routes, selected tabs, spinners, pagination controls,
and so on.
Managing this ever-changing state is hard. If a model can update
another model, then a view can update a model, which updates another
model, and this, in turn, might cause another view to update. At some
point, you no longer understand what happens in your app as you have
lost control over the when, why, and how of its state. When a system
is opaque and non-deterministic, it's hard to reproduce bugs or add
new features.
As if this wasn't bad enough, consider the new requirements becoming
common in front-end product development. As developers, we are
expected to handle optimistic updates, server-side rendering, fetching
data before performing route transitions, and so on. We find ourselves
trying to manage a complexity that we have never had to deal with
before, and we inevitably ask the question: is it time to give up? The
answer is no.
This complexity is difficult to handle as we're mixing two concepts
that are very hard for the human mind to reason about: mutation and
asynchronicity. I call them Mentos and Coke. Both can be great in
separation, but together they create a mess. Libraries like React
attempt to solve this problem in the view layer by removing both
asynchrony and direct DOM manipulation. However, managing the state of
your data is left up to you. This is where Redux enters.
Following in the steps of Flux, CQRS, and Event Sourcing, Redux
attempts to make state mutations predictable by imposing certain
restrictions on how and when updates can happen. These restrictions are reflected in the three principles of Redux.
But there are many cases where you won't need redux, it's important to understand what it does, and why you would need it.
I personally didn't use Redux in any of project I started over the last couple of year or so. I don't expect to use it in future either. Here's why.
Redux was revolutionary when it appeared in 2015. It brought two big ideas to React:
It combined action-based model of Flux with a concept of Reducer (It is in its name: "Red" "ux" = "Red"ucer + Fl"ux"). That Action - Reducer pattern instantly gained traction among React programmers.
It solved an application-wide state. Let's say we had certain data that we wanted to make available throughout the app. Before Redux the only reliable way to do that was to pass that data through props to child components... and then to their child components, and so on. Redux changed that. It allowed pieces of data to transcend the entire component hierarchy of an application without passing that data through props from one component to another. It also provided a convenient way to access and manipulate that application state from anywhere in the application.
Redux used a context API under the hood, which at the time was intended for React internal use only and was cumbersome to use.
Fast forward to 2019. A lot has changed. We now have hooks and the stable public context API which is ready for the prime time. An action - reducer pattern is now readily available via useReducer hook. We don't need Redux for that any more.
The modern React context API is simpler, more efficient than before and comes with hooks support. In most cases, wrapping your application state in a context is all you need to access it anywhere in your app.
So what about Redux?
My point of view that in a vast majority of cases you don't need Redux any more. Contexts and hooks get the job done most of the time. If you still think that contexts are not very friendly you may have a look at unstated-next library which is just a thin wrapper on top of the context API. That whole library is just 200 bytes!
However, plugging Redux into your project may be warranted if:
you want to take advantage of Redux middlewares such as redux-thunk
or you love Redux developer tools with their time-travelling ability.
In that case, make sure you know what you are doing. Redux magic comes with a price.
Redux is a complicated beast. It will bring a lot of complexity into your app. Some of that complexity is obvious while many other unobvious gotchas are hidden and waiting for you to trip on it. Think twice if you want to deal with that. Even then it is worth checking out alternatives such as MobX or react-sweet-state.
origin: You may not need redux
React ships with all the features you need to handle your state without a single additional library. Most of your application's states should not be global as they live just fine in a useState or useReducer or custom hook next to your components.
So before you dive into the world of advanced state management (e.g. Redux), consider using the tools React ships with out of the box.
If you are interested in learning a bit more about this, I'd recommend this article by Andy Fernandez: https://www.scalablepath.com/react/context-api-vs-redux

Is Redux.js a sufficient way to separate data from view in a React.js/Node.js hybrid application?

I am quite new to web programming. I've started developing a single-page web application using React.js with a Node server.
I've read the tutorial, played with boilerplates, and quickly I understood React would take care only of the view aspect. So I tried to put my data-processing functions with the export keyword in a JavaScript file so I could use them in my React components. But that way was pretty "dirty" and it didn't feel satisfying at all.
Then I looked for a way to effectively separate the model and the controller from the view, so that I could completely change the GUI with little effort, and thus allow the project to grow and multiple people to work on it at the same time.
I've came across this article explaining the Flux architecture, and I saw a major implementation to use with React.js was Redux.js. I was quite surprised that I didn't see it at first, and now I wonder how much frameworks one has to use when working with JavaScript and Web.
My question is simple : is Redux.js all I need to effectively separate data, treatments and GUI components ? Or did I miss something else ? Are there any other major architectures you would recommend ?
Many thanks,
Redux is generally used to contain all the data that your app needs. It acts like a store which can pass the required data to the components that actually needs the data. For example, if you need a particular data fetched from an ajax request to be distributed among two components, then redux is a perfect fit. Whether you need redux depends on how your app is structured. If you have an app with a large number of components and most of these require data from your server or api, I'd suggest you go with redux. Once you learn it, it's incredibly simple. And yes, redux is all you need to separate data from ui. To get a nicely formatted structure, put together all your ajax requests under a folder and export it so that you can call it from the ui component. And when you receive the data pass the payload to the redux store which will automatically pass it to all the components which are connected to that particular reducer. For details on how to connect react with redux, check out their documentation:
https://redux.js.org/basics/usage-with-react
Remember not to confuse the state mentioned in redux with the state in react. Redux state refers to the application state. Do check it out and if doesn't work for you, another alternative would be flux.

Does Redux care how my API is structured?

As I'm diving into Redux this is the question that is stuck with me the most. There are tons of articles and tutorials about Redux but it seems there are lots of different opinions on how to deal with APIs.
In my case, I'm working on a full stack web app that will use two APIs to collect the necessary data we need for our React front-end.
REST API #1 will be developed outside of my web application, most likely written with Python/Flask.
REST API #2 is a Node/Express app that will communicate with API #1. And it will serve endpoints directly to our React/Redux front-end.
Now in our past applications, we structure our back-end with your typical data model and a controller to communicate with the front-end through an endpoint.
I think my confusion is coming in here. Is there a correct/incorrect way to build a REST API that needs to communicate with React/Redux? I like this diagram, but it obviously doesn't say anything specific about the API structure. Does Redux not care about the back-end structure? Can I build an endpoint as I described above and have Redux just call the appropriate endpoint?
It is my understanding that Redux does not care about the structure of the API endpoint. You can use whatever middleware you see fit (Redux Saga, redux promises, redux thunk).
This redux boilerplate should help understand one way of handing redux side effects using redux-thunk. The boilerplate also presents an example server side api using expressjs and mongodb utilizing the MVC paradigm.
This is the redux-saga example.

Good solution to work with rest-api like SPA with redux?

I'm trying to implement admin-site for commenting-system. I have REST-API with JSON. I don't want do isomorphic application. I just want feel in Single Page manner. I see there is already has some solutions:
1) Create ajax factory and send request to api methods with XmlHttpRequest, during dispatch action and handling this by hands.
2) Redux-api or redux-rest.
3) Method that used in redux real-world example.
For my job i need's stable solution. I think to choose redux-api. But i don't know which disadvantages can be in each variant.
Maybe anyone has the same problem?
There's no definitive answer to this; however I am using a variant of redux-api-middleware which allows me to keep my action creators stateless and free of side effects.
redux-api and redux-rest both look valid; if somewhat 'magic' based on the amount of configuration / convention they enforce on your app.

Categories