BCT
BCT

Reputation: 75

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).

Upvotes: 4

Views: 5741

Answers (2)

Rajat Dhoot
Rajat Dhoot

Reputation: 185

If you are new then I recommend to use package instead of creating your own you can find many package.

one of them you can see here https://www.npmjs.com/package/react-loader-advanced

you can use like

import Loader from 'react-loader-advanced';

class Example extends Component {
render() {
    if(!loaded) {return (<Loader show={true} message={<i className='material-icons spinner-icon'>autorenew</i>}></Loader>  )}
 }
}

You can pass spinner or text you want. You can read more on github

Upvotes: -1

hamzo
hamzo

Reputation: 195

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);

Upvotes: 8

Related Questions