Converting functions from pure react to redux react

react and redux
react-redux tutorial
add redux to react app
add redux to existing react app
react-redux example
mapdispatchtoprops
mapstatetoprops
react-redux connect example

In pure react, I have written a function that I call in componentDidMount ():

  getTasks = (userId, query, statusTask, pageNumber) => {
    let check = {};
    axios({
      url: `/api/v1/beta/${userId}`,
      method: 'GET'
    })
      .then(res => {
        check = res.data;

        if (res.data) {
          this.setState({
            checkRunning: res.data,
            checkRunningId: res.data.id
          });
          this.utilizeTimes(res.data.task_id);
        }
      })
      .catch(error => {
        console.log(error);
      })
      .then(() => {
        const params = {
          sort: 'name'
        };

        if (query) {
          params['filter[qwp]'] = query;
          if (this.state.tasks[0]) {
            this.setState({
              selectedId: this.state.tasks[0].id,
              selectedTabId: this.state.tasks[0].id
            });
          }
        }

        axios({
          url: '/api/v1//tasks',
          method: 'GET',
          params
        })
          .then(res => {
            if (res.status === 200 && res.data) {
              this.setState({
                tasks: res.data,
                lengthArrayTasks: parseInt(res.headers['x-pagination-total-count'])
              });

              if (!check && res.data && res.data[0]) {
                this.setState({
                  selectedTabId: res.data[0].id,
                });

                this.load(res.data[0].id);
              }

              let myArrayTasks = [];
              myArrayTasks = res.data;
              let findObject = myArrayTasks.find(task => task.id === this.state.runningTimerTask.id);

              if (
                !findObject &&
                this.state.runningTimerTask &&
                this.state.runningTimerTask.id &&
                this.state.query === ''
              ) {
                this.setState({
                  tasks: [this.state.runningTimerTask, ...myArrayTasks]
                });
              }
            }
          })
          .catch(error => {
            console.log(error);
          });
      });
  };

I am trying to rewrite it to redux, but with poor results. First it makes one request / api / v1 / beta / $ {userId}, writes the answer in the variable check. check passes to the nextthen. In the next then carries out the request '/ api / v1 // tasks' Can somebody help me? I am asking for some tips. Is this somehow complicated?

So far, I've managed to create something like this:

store

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from '../reducers';

const store = createStore(rootReducer, applyMiddleware(thunk));

export default store;

actions

export const RUNNING_TIMER = 'RUNNING_TIMER';
export const GET_TASKS = 'GET_TASKS';
export const FETCH_FAILURE = 'FETCH_FAILURE';

export const runningTimer = (userId, query, statusTask, pageNumber) => dispatch => {
  console.log(userId);
  axios({
    url: `/api/v1/beta/${userId}`,
    method: 'GET'
  })
    .then(({ data }) => {
      dispatch({
        type: RUNNING_TIMER,
        payload: data
      });
    })
    .catch(error => {
      console.log(error);

      dispatch({ type: FETCH_FAILURE });
    })
    .then(() => {
      const params = {
        sort: 'name'
      };

      axios({
        url: '/api/v1//tasks',
        method: 'GET',
        params
      })
        .then(({ data }) => {
            dispatch({
                type: GET_TASKS,
                payload: data
            });
        })
        .catch(error => {
            console.log(error);
        });
    });
};

reducer

import { RUNNING_TIMER, GET_TASKS } from '../actions';

const isRunningTimer = (state = {}, action) => {
  const { type, payload } = action;
  switch (type) {
    case RUNNING_TIMER:
      return {
        checkRunningTimer: payload,
        checkRunningTimerId: payload && payload.id ? payload.id : null
      };
      break;
      case GET_TASKS:
      return {
        tasks: payload,
        lengthArrayTasks: parseInt(action.headers['x-pagination-total-count'])
      };
    default:
      return state;
  }
};

const rootReducer = combineReducers({ isRunningTimer });

export default rootReducer;

App

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React'
    };
  }

  componentDidMount() {
    this.props.runningTimer();
  }

  render() {
    return (
      <div>

      </div>
    );
  }
}

const mapStateToProps = state => {
  const { isRunningTimer } = state;

  return {
    isRunningTimer
  };
};

const mapDispatchToProps = dispatch => ({
  runningTimer: (userId, query, statusTask, pageNumber) => dispatch(runningTimer()),
});

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);
Number 1 Consider your state design.

I find it useful to consider what the state object would look like at a given point in time.

Here is an example of initialState used in an application of mine.

const initialState = {
        grocers: null,
        coords: {
            latitude: 37.785,
            longitude: -122.406
        }

    };

This is injected at the createStore.

Breaking down your application state object/properties, should assist you in making your actions simpler as well.

Number 2

Consider breaking down your actions.

My thoughts, decouple the action code, at the .then at the second .then .(Consider saving the results somewhere in a user: object)

        .then(response => {
          const data = response.data.user;
          setUsers(data);})
        .catch(error => {
            console.log('There has been a problem with your fetch operation: ' + error.message);
        })

    function setUsers(data){
        dispatch({
            type: FETCH_USERS,
            payload: data
        });
    }

This refers to the S in SOLID design principles. Single Responsibility Principle.

https://devopedia.org/solid-design-principles

Number 3

Consider this, if the 'getUser' info fetch fails.

Having the process/response separated will allow the application to be debugged more cleanly. In example, the user api failed or the getTask api failed, etc.


More resources on redux. https://redux.js.org/introduction/learning-resources#thinking-in-redux

React 101, Part 2: Refactoring with Redux, Todo.js function mapStateToProps(state, ownProps) { const { visibilityFilter } different parts of the state tree, and transforming the store data in different ways. mapStateToProps Functions Should Be Pure and Synchronous. The only difference between React Hooks and React Redux is that the “dispatch” function name is reserved in React Redux. In React Hooks we create our own “dispatch” function name through the useReducer hook. To call the dispatch function in React Redux we use the syntax this.props then the name of the property in mapDispatchToProps

Extending previous answer from @Cullen, this is what I did:

  1. Since you already have a action to GET_TODOS, just make the action creator for runningTimer to do one and only one thing - make API call to /api/v1/beta/<userId> and dispatch respective actions.
export const runningTimer = (
  userId,
  query,
  statusTask,
  pageNumber
) => dispatch => {
  return axios({
    url: `/api/v1/beta/${userId}`,
    method: "GET"
  })
    .then(({ data }) => {
      dispatch({
        type: RUNNING_TIMER,
        payload: data
      });
    })
    .catch(error => {
      console.log(error);

      dispatch({ type: FETCH_FAILURE });
    });
};

  1. Update props of your app component to read store data.
...
const mapStateToProps = state => {
  const { isRunningTimer, todos, todo } = state;

  return {
    todos,
    todo,
    isRunningTimer,
  };
};

const mapDispatchToProps = dispatch => ({
  getTodos: () => dispatch(getTodos()),
  getTodo: id => dispatch(getTodo(id)),
  runningTimer: (userId, query, statusTask, pageNumber) => dispatch(runningTimer(userId)),
});
...
  1. Update the implementation of componentDidMount to dispatch isRunningTimer -
componentDidMount() {
...
    // call with userId 1
    this.props.runningTimer(1).then(() => {
      console.log(this.props);

          // additional params for getTasks
      const params = {
        sort: 'name'
      };

      // another call for getTodos with names sorted
      this.props.getTodos(params);
    });
...

Note: You need to update your getTodos action to take in an optional params arguments (which is initialized to empty object if not passed).

Hope this helps you.

Live sandbox for this is present here - https://stackblitz.com/edit/react-redux-more-actions

Connect: Extracting Data with mapStateToProps · React Redux, In pure react, I have written a function that I call in componentDidMount () : getTasks = (userId, query, statusTask, pageNumber) => { let check  Pure functions do not have any observable side effects, such as network or database calls. The pure functions just calculate the new value. You can be confident that if you call the pure function with the same set of arguments, you're going to get the same returned value. They are predictable.

Check out React-boilerplate. Great boilerplate for react and redux. They use redux-saga and redux-hooks as well.

Converting functions from pure react to redux react, It is a pure function that returns a copy of the state with the new change. A neat feature of Redux is that we can have many reducers, and combine  If you work with React frequently, this should all look pretty standard. Now let’s convert it to a functional component using the useState Hook. Converting to a Function. First, create an additional Form component in the components folder. Title it FunctionBasedForm.js. We’ll use this component to build an identical form using the useState

Using Redux with React: Complete Tutorial with Real-World , Learn step-by-step process of adding Redux to your React project with an easy-​to-follow A reducer is a pure function that accepts 2 parameters: state and action. Let's convert our <h1> tag into a Container Component. Why Redux need reducers to be “pure functions” You may have heard that Redux depends on “pure functions” from functional programming. Well, what exactly does that mean? The picture below shows a simple Todo app from Redux examples. It currently has four tasks.

Step-By-Step: How to Add Redux to a React App, As seen in our previous tutorial, React “flows” data through components. Reducers should be written as “pure” functions, a term that describes a function with the following This example has been slightly converted from the original. It uses  Pure React: The core concepts of React, in isolation, without Redux, Webpack, and the rest. Learning everything at once is massively overwhelming. So in this book, we will take a different approach. A more sane approach. We will learn Pure React.

Leveling Up with React: Redux, Basically, a stateless functional component doesn't support any of the usual React lifecycle methods (or 'state', obviously). It's just a function  connect() Overview. The connect() function connects a React component to a Redux store.. It provides its connected component with the pieces of the data it needs from the store, and the functions it can use to dispatch actions to the store.

Comments
  • You might find this answer useful. stackoverflow.com/a/58216027/1263904 It also has a sandbox to play around.
  • @pritam Can we talk on chat?
  • What is runningTimer in runningTimer: (userId, query, statusTask, pageNumber) => dispatch(runningTimer()), the runintTimer() part?
  • @HMR should be const mapDispatchToProps = dispatch => ({ runningTimer: (userId, query, statusTask, pageNumber) => dispatch(runningTimer(userId, query, statusTask, pageNumber)) });
  • @HMR runningTimer it is action
  • Look at my component in pure Rect. I can't decouple .then
  • You can separate at the second .then, I have inserted an example to wrap and 'close' that action up. Name and seperate those actions using your own thoughts.
  • Look at my function in pure React is complicated. Compare your function with mu function in pure react. In your function doesn't have a few elements
  • Well, pls don't expect a full answer. We guys can give you insights on how to do a thing, take a pen and paper and simplify your workflow. You'll get better understanding of how you should go about adding those missing pieces. If you'd like to chat, do let me know how and when you'd want to.