Update redux state outside React component - reactjs

I have a react project configured with redux for state management.
For api calls I use a file called axiosInstance. In this file I need to have access to redux store (and I have access importing store and using getState - store.getState()). Now the problem is that I want also to update the redux state from this file (axiosInstance).
How I can update redux store from this file (which is not a react component) in a efficient method?

Okay, I assume that you are using Axios for the network calls.
tl;dr
Use store.dispatch(action) and action to make changes to store state
Yes, the store can be accessed with store.getState(), you can also change state with store.dispatch(action). as per the docs
Dispatches an action. This is the only way to trigger a state change.
The store's reducing function will be called with the current getState() result and the given action synchronously. Its return value will be considered the next state. It will be returned from getState() from now on, and the change listeners will immediately be notified.
This happens because of the functional paradigm that redux follows (google for more).
Now, the action has to be defined with an actionCreator, or simply you could call .dispatch() with an inline object with one string property as {type: 'name-of-action'}. This prompts the store to change the state.
You may require redux-thunk for async actions.
Conclusion:
Let's save some trouble here as you may have many calls to the store, you can create a context that handles the AxiosInstance (as there is already a different file for that).
Make a context in the AxiosInstance file and then you can start dispatching actions as per the network responses. this will save you a lot of trouble as the state is updated by redux without actually looking at it much.

Related

Why should you dispatch an action to update the state and not update the store directly in react/redux?

Explain briefly about... Why should you dispatch an action to update the state and not update the store directly in react/redux?
Redux is a dataflow pattern that is event (=action)-based. Only actions lead to store changes. Also, those have to happen without changing the old state, but by creating a new one.
This is a base assumption and un-bendable rule, because that is the purpose of Redux - moving applciation logic out of your UI layer.
All tooling depends on that assumption - e.g. react-redux will only check for new state after a dispatch and it will do so by comparing current and last state value.
If you want to directly modify it, you simply have gone for the wrong library.
There are libraries that allow for such things, like mobx or valtio, but it will not work with Redux.

ReactJS constants that changes dynamically(Dynamic global)

What would be the best way, while following React best practices, to define globals that changes according to props provided by a redux state.
For example, let's say I have a metric or imperial toggle value that's dispatched into a persisted redux state. Is it possible to call for a constant that changes its value based on the toggle without providing the current state of the toggle by passing it via props?
My current implementation is doing
globals.distance(this.props.metric)
where this.props.metric is mapped from the redux state to the component's props. I want to somehow implement subscription to the redux state from within the globals file, so I can just do constants.distance. I've tried importing getState() as well as subscribing to changes in the redux state, but the problems there is that getState() only runs once when the file gets loaded, and I can't seem export constants subscribed to the state since the function returns an unsubscribe function. I can also create a Component and subscribe that to the redux state, but I can't seem to find an easy way to export constants from within a Component state either.
Well, I couldn't find a solution I liked, so I made my own. It's a thin wrapper to connect functions to the Redux store and return a value.

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

Initialising State in React Redux app with data in server

I am working on my first React Redux project.
The project depends on a server to get its data and therefore there is also a server API that needs to be called in order to get those data.
My question is about initialising state.
There are 2 ways I can think of initialising state:
1.) First pass an empty object {} as the initialised state of the Redux store then inside componentDidMount that is where I call the API to access the data in the server and then update the state of the store/app then.
2.) In the reducer of the Redux app call all relevant server method (e.g. getCategories(), getPosts(), etc.) then compose a object with all of the data e.g. {categories: categories, posts: posts} then pass this object to the reducer as the initial state.
Which way is the recommended way for Redux when dealing with data stored in the server?
If there is a 3rd or 4th way that is the Redux way or the recommended way then please share your knowledge. Thank you.
The way I work with data coming from the back end, and as far as I know is also the suggested way, is this:
In the componentDidMount method call a thunk action creator. you can read more about them in this link.
Inside that thunk action creator you first dispatch a REQUEST action, then perform a fetch to access the back end and when the response arrives you handle it on either the success or error handlers. Depending on the handler executed you dispatch either a SUCCESS or an ERROR action (and you attach to it all the relevant information that is coming from the back end so the reducer can access it).
In your reducer you write code to handle all the above actions (REQUEST, SUCCESS and ERROR). Each handler will transition your state, for instance the REQUEST can set an isFetching flag to true that will let you show a spinner in the UI, and the SUCCESS can set that flag to false and populate the state with the data coming from the back end and passed to the reducer using the action dispatched.
Once your reducer is updated, you will access that updated state from the UI, for instance using the connect react-redux function.
Regarding the initial state, it should represent a default state. for instance, it will have the isFetching flag in false and, if you are fetching a list of foods from the back end, then that list could be an empty list in your initial state. This is just a for instance of course. You need to set an initial state that makes sense to your app.
I hope this helps you.
The first way is the better way of initializing state. Your component makes the necessary API calls in componentDidMount and passes the data to Redux as payload of actions which the reducers use to update the state of your application.
The second way is not advisable. According to the Redux docs:
The reducer is a pure function that takes the previous state and an action, and returns the next state.
(previousState, action) => newState
...
It's very important that the reducer stays pure. Things you should never do inside a reducer:
Mutate its arguments;
Perform side effects like API calls and routing transitions;
Call non-pure functions, e.g. Date.now() or Math.random().
Edit:
You can also use thunk middleware and async actions to do API calls as explained in the Redux docs and #DiegoTArg's answer.

Accessing getState() in a non-Action file nor Component

Is there any way I can access getState() from a non-React Component nor an Action file?
I have a Util file that needs to be able to call getState() (or just any way to get the most updated state). Usually I just pass in part of the state that I need for the function, but I have one particular function that loops and needs to get the latest function every time it does loop.
I was reading more into connect() but it seems like it only works for Components. I was looking into Middleware, but it seems like that only interacts with executing Actions and I'm just at a road block where I don't know how to move forward.
Thank you
You might consider leveraging the subscribe(listener) method in the Redux Store.
The subscribe method allows you to attach a callback that is called every time the state tree may have potentially changed. This would let you call getState() inside the listener to get the current state tree.
The subscribe method is a low level API and is a bit clunky. The documentation for Redux also provides some linking to examples leveraging the Observable property of the Redux store so you can do something a bit more abstracted.

Resources