4

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

2 Answers 2

8

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);
Sign up to request clarification or add additional context in comments.

Comments

-1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.