Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create loader spin for react/redux

My project need loader spin to use for every component when get data from database but I don't know how to do. For now I just have pre-loader for open the page at first time (CSS).

like image 667
BCT Avatar asked Mar 08 '23 03:03

BCT


1 Answers

Let's say you want to get charts data from /charts endpoint.

//action
export const fetchOrdersChartsData = () => dispatch => {
    dispatch({ type: CHARTS_LOADING }); //Loading starts
    api.get('/charts')
      .then(charts => 
        dispatch({
          type: CHARTS_LOADED, //Loading ends
          payload: charts.data,
        }))
      .catch(error => {
       //dispatch error 
      });
  };

//reducer
export default (state = initState, action) => {
  switch (action.type) {
    case CHARTS_LOADING:
      return {
        ...state,
        loading: true,
      };
    case CHARTS_LOADED:
      return {
        ...state,
        charts: action.payload,
        loading: false,
      };
    default:
      return state;
  }
};

In your component you can track loading state and show/hide loader based on that.

import React from 'react'
import { connect } from 'react-redux';
import Loader from './Loader'
import Chart from './Chart'

class Charts extends React.PureComponent{
    render(){
        const {loading} = this.props;
        return(
            <div>
                {loading ? <Loader/> : <Chart/>}
            </div>
        )

    }
}


export default connect(
    state => ({
      loading: state.charts.loading,
    }),{})(Accumulation);
like image 132
hamzo Avatar answered Mar 17 '23 02:03

hamzo