Y
Y
Yura Komarov2019-08-05 17:05:18
redux
Yura Komarov, 2019-08-05 17:05:18

How to use redux in different js classes?

Good day everyone.
I want to deal with the redux library.
What am I doing
app.js file

import {applyMiddleware, createStore} from 'redux';
import {composeWithDevTools} from 'redux-devtools-extension';
import thunk from 'redux-thunk';
import reducer from '../blocks/reducers';

const store = createStore(
  reducer(),
  composeWithDevTools(applyMiddleware(...[thunk])),
);

store.subscribe(() => {
  console.log('sub ', store.getState());
});

store.dispatch({type: 'ADD_TRACK', payload: 'Simple like spirit'});

index.js file in reducers folder
import {combineReducers} from 'redux';
import user from './playList';

export default () =>
  combineReducers({
    user,
  });

playList.js file in reducers folder
export default (state = [], action) => {
  if (action.type === 'ADD_TRACK') {
    return [...state, action.payload];
  }
  return state;
};

At this stage, everything is fine and working, and you can even write something by calling store.dispatch and change this store in the app.js file.
But this is all good, but I want that I could change the store from any class of my application, that is, I will now create a class, write a method in it, on click which should run to the server and receive data. Next, I will connect this class to app. js But I just don’t understand how to call store.dispatch in this class and throw this data into it.
The question is, how to connect redux correctly so that it would be possible for different classes to use one store?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2019-08-05
@Yurajun

You can use bindActionCreators or your own wrapper over the store.dispatch call and import actions already connected to the store into modules.
For asynchronous requests, redux-thunk can be used .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question