Coder Social home page Coder Social logo

mironov / react-redux-loading-bar Goto Github PK

View Code? Open in Web Editor NEW
935.0 10.0 94.0 13.66 MB

Loading Bar (aka Progress Bar) for Redux and React

Home Page: https://mironov.github.io/react-redux-loading-bar/

License: MIT License

JavaScript 100.00%
middleware redux react promise-middleware loading-bar progress-bar progress-simulation

react-redux-loading-bar's Introduction

React Redux Loading Bar

npm version build status coverage status npm downloads

A React component that provides Loading Bar (aka Progress Bar) for long running tasks.

Demo GIF

Consists of:

  • React component — displays loading bar and simulates progress
  • Redux reducer — manages loading bar's part of the store
  • (optional) Redux middleware — automatically shows and hides Loading Bar for actions with promises

Examples

See Demo or its source code.

Installation

npm install --save react-redux-loading-bar

Usage

Mount the LoadingBar component anywhere in your application:

import LoadingBar from 'react-redux-loading-bar'

export default class Header extends React.Component {
  render() {
    return (
      <header>
        <LoadingBar />
      </header>
    )
  }
}

Good news is that it doesn't include any positioning. You can attach it to the top of any block or the whole page.

You can even include multiple loading bars on the same page, that will render independently. They need to be provided with a scope so that you can adjust them independently.

import LoadingBar from 'react-redux-loading-bar'

export default class Header extends React.Component {
  render() {
    return (
      <header>
        <LoadingBar />
      </header>
      <section>
        <LoadingBar scope="sectionBar" />
      </section>
    )
  }
}

Install the reducer to the store:

import { combineReducers } from 'redux'
import { loadingBarReducer } from 'react-redux-loading-bar'

const reducer = combineReducers({
  // app reducers
  loadingBar: loadingBarReducer,
})

Apply middleware to automatically show and hide loading bar on actions with promises:

import { createStore, applyMiddleware } from 'redux'
import { loadingBarMiddleware } from 'react-redux-loading-bar'
import rootReducer from './reducers'

const store = createStore(
  rootReducer,
  // promise middleware
  applyMiddleware(loadingBarMiddleware())
)

Usage with custom suffixes or alternative promise middleware

You can configure promise type suffixes that are used in your project:

import { createStore, applyMiddleware } from 'redux'
import { loadingBarMiddleware } from 'react-redux-loading-bar'
import rootReducer from './reducers'

const store = createStore(
  rootReducer,
  applyMiddleware(
    loadingBarMiddleware({
      promiseTypeSuffixes: ['REQUEST', 'SUCCESS', 'FAILURE'],
    })
  )
)

Usage with custom scope (for multiple loading bars)

import { createStore, applyMiddleware } from 'redux'
import { loadingBarMiddleware } from 'react-redux-loading-bar'
import rootReducer from './reducers'

const store = createStore(
  rootReducer,
  applyMiddleware(
    loadingBarMiddleware({
      scope: 'sectionBar',
    })
  )
)

If you're not using redux-promise-middleware or any other promise middleware, you can skip installing the loadingBarMiddleware() and dispatch SHOW/HIDE actions manually. The other option is to write your own middleware that will be similar to the bundled one.

Usage without middleware

You can dispatch SHOW/HIDE actions wherever you want by importing the corresponding action creators:

import { showLoading, hideLoading } from 'react-redux-loading-bar'

dispatch(showLoading())
// do long running stuff
dispatch(hideLoading())

You need to dispatch HIDE as many times as SHOW was dispatched to make the bar disappear. In other words, the loading bar is shown until all long running tasks complete.

Usage without middleware but with scope

You need to provide the scope to the actions:

import { showLoading, hideLoading } from 'react-redux-loading-bar'

dispatch(showLoading('sectionBar'))
// do long running stuff
dispatch(hideLoading('sectionBar'))

Usage with redux-saga

Install the loadingBarReducer() and mount Loading Bar in your application. You can import and dispatch showLoading and hideLoading from your sagas.

import { showLoading, hideLoading } from 'react-redux-loading-bar'

export function* fetchData() {
  try {
    yield put(showLoading())
    const payload = yield call(API, params)
    // payload processing
  } finally {
    yield put(hideLoading())
  }
}

Usage with immutable-js

You can change component import line if your top level redux store object is immutable.

import { ImmutableLoadingBar as LoadingBar } from 'react-redux-loading-bar'

// Mount LoadingBar component as usual

Usage with jQuery Ajax Requests

If you happen to use jQuery for Ajax requests, you can dispatch SHOW/HIDE actions on ajaxStart/ajaxStop global events:

$(document).on('ajaxStart', this.props.actions.showLoading)
$(document).on('ajaxStop', this.props.actions.hideLoading)

See a demo or checkout the code.

RTL (Right-To-Left) Layout

Pass direction="rtl" to make Loading Bar simulate progress from right to left:

<LoadingBar direction="rtl" />

Styling

You can apply custom styling right on the LoadingBar component. For example you can change the color and height of the loading bar:

<LoadingBar style={{ backgroundColor: 'blue', height: '5px' }} />

Alternatively, you can specify your own CSS class.

Please note that will disable default styling (which is background-color: red; height: 3px; position: absolute;).

<LoadingBar className="loading" />

Don't forget to set height, background-color and position for the loading class in your CSS files.

Configure Progress Simulation

You can change updateTime (by default 200ms), maxProgress (by default 90%) and progressIncrease (by default 5%):

<LoadingBar updateTime={100} maxProgress={95} progressIncrease={10} />

By default, the Loading Bar will only display if the action took longer than updateTime to finish. This helps keep things feeling snappy, and avoids the annoyingness of showing a Loading Bar for fractions of seconds. If you want to show Loading Bar even on quickly finished actions you can pass the showFastActions prop:

<LoadingBar showFastActions />

Reset progress

You can dispatch the resetLoading action to ultimately hide Loading Bar even when multiple long running tasks are still in progress.

Tests

npm test

Contributing

In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code.

Contributors (in chronological order)

To see what has changed in recent versions of Loading Bar, see the CHANGELOG.

Licensed MIT. Copyright 2016-current Anton Mironov.

react-redux-loading-bar's People

Contributors

danielruf avatar dengbupapapa avatar dependabot[bot] avatar greenpart avatar hieuhlc avatar hugomn avatar janslow avatar josefernand avatar larrydahooster avatar masterodin avatar mironov avatar neogermi avatar onchainguy-eth avatar vitosamson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-redux-loading-bar's Issues

resetProgress is called after the loading-bar was unmounted

VM789:27 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.

window.console.error @ VM789:27
printWarning @ warning.js:36
warning @ warning.js:60
getInternalInstanceReadyForUpdate @ ReactUpdateQueue.js:48
enqueueSetState @ ReactUpdateQueue.js:200
ReactComponent.setState @ ReactComponent.js:64
resetProgress @ loading_bar.js:98

props Children

Hi! I was trying to attach another div to <LoadingBar /> so that will block the component below. The idea is: when you click a button, after the dispatch I will lock the screen while showing the loading bar.

something like this.props.children will be usefull so I could do

<LoadingBar>
    <div block />
</LoadingBar>

Do you have another approach to sugest? I also created a Loading component that will render:

<div>
    <LoadingBar />
    <div block />
</div>

But while the LoadingBar disappears when needed the div below doesn't

Thanks! and great work, very useful and easy to implement

timeout until the loading bar is shown

Would be nice if it was possible to set an activation timeout. So that for fast actions (say under 300ms) the loading bar should not activate at all. This would make the UI less noisy in many cases.

Help me about loading bar in mxstbr/react-boilerplate

I used react-redux-loading-bar in mxstbr/react-boilerplate and maybe i wrong in config. Can you help me??

  • I added at root app
  • I added "loadingBar: loadingBarReducer" in root reducer (in combineReducers).
    And it's not working.. May I miss or something??

setState() called on an unmounted component if change path after success action

If you call browserHistory.push(somepath) after success action was dispatched, the next error would be:
setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component

Clearing interval in componentWillUnmount would resolve this issue.
I've added this in loading_bar.js and it helped me:

{
    key: 'componentWillUnmount',
    value: function componentWillUnmount() {
      var interval = this.state.interval;
      var percent = this.state.percent;
      clearInterval(interval);
      interval = null;
      percent = 0;
    }
  }

Loading bar doesn't disappear on immediately props changing

I've found a possible problem. I use loading bar just passing a loading prop:

const loading = ... // different calculations

<LoadingBar loading={loading} />

So I've noticed when at first loading is equal 1 or 2 or whatever number not equal 0 and then this variable is quickly changing to 0, LoadingBar doesn't disappear.

I prepared a quick demo. This demo is a useless and incorrect, but it helps to understand the problem.
If you open a browser console, you'll see very interesting logs like this:

componentDidMount loading 1
launch progressInterval 1
shouldStop progressInterval null
shouldStop loading 0
componentWillReceiveProps shouldStop null
shouldStop progressInterval null
shouldStop loading 0
simulateProgress progressInterval 1
simulateProgress progressInterval 1
simulateProgress progressInterval 1
simulateProgress progressInterval 1
simulateProgress progressInterval 1
...
simulateProgress progressInterval 1

These logs tell us shouldStop method returns null because progressInterval is null:

shouldStop(nextProps) {
  return this.state.progressInterval && nextProps.loading === 0
}

And also let's look at progressInterval variable changes:

progressInterval: 1
progressInterval: null
progressInterval: null
progressInterval: 1
progressInterval: 1
progressInterval: 1
progressInterval: 1
...
progressInterval: 1

I think the problem is here because there are setState calls dependent of state values like this:

let { progressInterval, percent } = this.state
...
this.setState({ progressInterval, percent })

You should use a function here:

this.setState((prevState) => {
  ...
  return { progressInterval, percent }
})

If you want to look at my demo here is its code

Loading Bar not showing up

Hi I am using react/redux with react-redux-loading-bar plugin here is my store and saga and UI component. Could any one tell what i am doing wrong here.

SAGA.js

const filterGetData = function* ( action ) {
  try {
    yield put(showLoading())
    const users = yield call(fetchUsers,action.payload);
    yield put({type: 'USERS_RECIEVED', users})
  } catch (error) {
  yield put({type: 'LOAD_USERS_FAILURE', error})
  }finally {
    yield put(hideLoading())
  }
};
export function* watchForUsers() {
  while(true) {
    const action = yield take('LOAD_USERS');
    yield fork(filterGetData, action);
  }
}

Index.js

const rootReducers = combineReducers({
  appReducer,
  loadingBar: loadingBarReducer,
})
const store = createStore(
  rootReducers,
  applyMiddleware(sagaMiddleware ,loadingBarMiddleware())
);
sagaMiddleware.run(watchForUsers);

Ui component

<header>
 <LoadingBar style={{zIndex: 99999}}/>
</header>

Can't make it work with redux-thunk

Hi,

I followed the readme but can't make it work with redux-thunk.

import { routerReducer as routing } from 'react-router-redux'
import { combineReducers } from 'redux'
import { loadingBarReducer } from 'react-redux-loading-bar'

const rootReducer = combineReducers({
  routing,
  loadingBar: loadingBarReducer,
});

export default rootReducer;
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk'
import { logger } from 'redux-logger'
import rootReducer from '../reducers'
import { loadingBarMiddleware } from 'react-redux-loading-bar'

export default function configureStore(preloadedState) {
  const store = createStore(
    rootReducer,
    preloadedState,
    applyMiddleware(thunk, loadingBarMiddleware(), logger)
  );
  return store;
}

Also added <LoadingBar />
Can you please tell me where to look?

Showing bar for custom width fails

First of all, thanks for the plugin it works well, though I am finding some issues while it displays with added margin, see the screenshot below

2017-06-15_16-05-10

What is happening is, I have a top nav bar in which I have added the Loader component which is supposed to show the loader from left 60px of the top bar, for this I have added marginLeft:60px which works well it starts leaving 60px from left, but when it finishes it crosses the header tag and goes beyond limit, see the screenshot which cause scroll bars to come up in the page.

Below is my code of Loader

const Loader = () => {
  return (
    <header style={{height:'3px',marginTop:'15px',marginLeft:'60px'}}>
      <LoadingBar style={{ backgroundColor: 'red', height: '3px', zIndex:9999, width:'100%', paddingRight:'60px' }} showFastActions updateTime={500} />
    </header>
  );
};

I tried to manipulate the width to some random value from 100%, it did work the progress bar was limited to that, but this is not way it should work, the progress bar should never go beyond header..

Any solution?

Thanks.

Force hide loading

Hi guys,

Thanks for the work you've done with the react-redux-loading-bar.
I am using react-redux-loading-bar without a middleware and I found myself in need for "force hide loading bar" functionality.
Meaning I need the ability to hide the loading bar with no consideration to how many times SHOW has been dispatched.
Do you plan on developing this ability?
Thanks

Bar showing and hiding delayed

I trigger the loading bar manually for my fetch requests by dispatching showLoading() before the fetch and hideLoading() after I received data. Although the loading bar shows, animates and then hides, everything is delayed! It almost looks like nothing is happening on showLoading() and the bar only shows once hideLoading() is called. Then it stays there for a default time and disappears.

Here is the part of my custom middleware action, where I dispatch the actions around the API call:

  store.dispatch(showLoading())
  console.log("SHOW")

  next({
    type: requestType,
    [ pendingTask ]: begin
  })


  // Passing the authenticated boolean back in our data will let us distinguish between normal and secret quotes
  return callApi(endpoint, authenticated).then(
    response => {
      store.dispatch(hideLoading())
      console.log("HIDE")
      return next({
        response,
        authenticated,
        receivedAt: Date.now(),
        type: successType,
        [ pendingTask ]: end
      })
    },
    error => {
      store.dispatch(hideLoading())
      return next({
        error: error.message || 'There was an error.',
        type: errorType,
        [ pendingTask ]: end
      })
    }
  )

The console.log outputs next to the dispatches appear much earlier than the bar appears. I didn't measure it, but it might be a fifth of a second or more.

The completion and hiding of the bar is only delayed for short running requests. If the request runs longer (say 2 seconds or more), the bar seems to complete and hide once the request finished (and I see the "HIDE" message in the console).

The <LoadingBar /> tag uses the default values. But even playing with the params did not fix the delay.

Am I missing something?

UPDATE:

Here you can see the behavior. When loading-bar/SHOW action is triggered, nothing happens. Only slightly before the loading-bar/HIDE action is triggered, does the bar appear and begin to move. Then, after the request has already finished, the bar still takes time to animate to 100% and finally disappear.

screenflow

Crash on IE11

Hi,

My app works on all browsers except IE11, which for some reasons I have to support it. Here is the error message from console:

DOM7011: The code on this page disabled back and forward caching. For more information, see: http://go.microsoft.com/fwlink/?LinkID=291337
localhost:3000
HTML1300: Navigation occurred.
localhost:3000
The above error occurred in the <LoadingBar> component:
    in LoadingBar (created by Connect(LoadingBar))
    in Connect(LoadingBar) (at main.component.js:20)
    in Router (created by BrowserRouter)
    in BrowserRouter (at main.component.js:18)
    in Provider (at main.component.js:17)
    in Main (at App.js:40)
    in ApolloProvider (at App.js:39)
    in App (at index.js:13)

React will try to recreate this component tree from scratch using the error boundary you provided, App.
SCRIPT438: Object doesn't support property or method 'includes'
bundle.js (85239,9)

It seams problem is related to includes method for objects which is not available in IE11, I find a stack overflow question about it but I not expert on that area.
can you please check it maybe it can help to fix the problem?

BTW thanks for awesome work 👍

Unsupported

Hi.
I tryed to install and got this error:

npm ERR! notsup Unsupported
npm ERR! notsup Not compatible with your operating system or architecture: [email protected]
npm ERR! notsup Valid OS: darwin
npm ERR! notsup Valid Arch: any
npm ERR! notsup Actual OS: linux
npm ERR! notsup Actual Arch: x64

Darwin?! My system not compatible with loading-bar... Sounds strange...

Immutable TypeError: Cannot call a class as a function

I configure store like this

const initialState = fromJS({});
const store = createStore(reducer, initialState, compose(
	applyMiddleware(sagaMiddleWare, routerMiddleware(history), promiseMiddleware(), loadingBarMiddleware()),
	window.devToolsExtension ? window.devToolsExtension() : f => (f)
));

If I use Immutable in reducer like bellow, it pulls out error:
TypeError: Cannot call a class as a function

import { combineReducers } from 'redux-immutable';
import { reducer as form } from 'redux-form/immutable';
import { ImmutableLoadingBar as LoadingBar  } from 'react-redux-loading-bar';

export default combineReducers({
    form,
    LoadingBar
});

TypeError: Cannot read property 'default' of undefined

Just installed react-redux-loading-bar in a kriasoft/starterkit-redux based application and I got following error:

TypeError: Cannot read property 'default' of undefined
at Function.mapStateToProps [as mapToProps] (/XXX/node_modules/react-redux-loading-bar/build/loading_bar.js:250:30)
at mapToPropsProxy (/XXX/node_modules/react-redux/lib/connect/wrapMapToProps.js:54:46)
at Function.detectFactoryAndVerify (/XXX/node_modules/react-redux/lib/connect/wrapMapToProps.js:63:19)
at mapToPropsProxy (/XXX/node_modules/react-redux/lib/connect/wrapMapToProps.js:54:46)
at handleFirstCall (/XXX/node_modules/react-redux/lib/connect/selectorFactory.js:37:18)
at pureFinalPropsSelector (/XXX/node_modules/react-redux/lib/connect/selectorFactory.js:85:81)
at Object.runComponentSelector [as run] (/XXX/node_modules/react-redux/lib/components/connectAdvanced.js:43:25)
at Connect.initSelector (/XXX/node_modules/react-redux/lib/components/connectAdvanced.js:195:23)
at new Connect (/XXX/node_modules/react-redux/lib/components/connectAdvanced.js:136:15)
at resolve (/XXX/node_modules/react-dom/cjs/react-dom-server.node.development.js:2086:14)

Hideloading not hiding the progress bar

Hi,

I am using showLoading and hideLoading with redux forms. On successful form submission and return results, I am hiding the bar, but the loading bar is not getting hidden.

simpletask (values) 
  {
      const {reset} = this.props
      this.props.dispatch(showLoading())
      return promise_returned(values.nPassword)
          .then(function(){
            this.props.dispatch(hideLoading())  **>> this hideLoading is not working**
            reset();
          })
          .catch( function(err){
              this.props.dispatch(hideLoading())  
              throw new SubmissionError({ _error: err.message })
            }
        );
  }

The state keeps getting appended
Object {form: Object, loadingBar: 1} (for first time)
In fact my other forms are all working fine with redux-forms and following the same pattern. Let me know if i am required to provide further info

Unsafe legacy lifecycles warning

I use the latest build of react and I get this warning in my console.

warning.js?6327:33 Warning: Unsafe legacy lifecycles will not be called for components using new component APIs.

Connect(LoadingBar) uses getDerivedStateFromProps() but also contains the following legacy lifecycles:
  componentWillReceiveProps
  componentWillUpdate

The above lifecycles should be removed. Learn more about this warning here:
https://fb.me/react-async-component-lifecycle-hooks

How to make loading bar loops

Hi,

I am wondering if I can make loading bar move in a loop until the components finishes loading. When there are multiple long running fetches, the current implementation makes me wonder if it hung.

Thank you!

Promise middleware does not support 'scope' property

The promise middleware here does not support any custom properties on the action except for type, payload and meta. Therefore, this library's middleware should check for the scope property within the meta property of the action, not on the action itself.

Add support for react-redux 5.x

A new redux version was just released. I think the API is backward compatible and thus it should be no problem to add redux 5.x also to the peer dependency of this package.

Percent value isn't reset when animationTimeout is cleared

Thank you for your quick answers on the previous issues.

When the animationTimeout is cleared on the launch function the percent isn't reset to 0 , so on the next showLoading action the bar isn't displayed.
I put bellow a workaround that seems to solve this:

function launch() {
var progressInterval = this.state.progressInterval;
var animationTimeout = this.state.animationTimeout;
var percent = this.state.percent;

if (!progressInterval) {
progressInterval = setInterval(this.boundSimulateProgress, this.props.updateTime);
clearTimeout(animationTimeout);
percent = 0;
}

this.setState(_extends({}, this.state, { progressInterval: progressInterval }, {percent: percent}));
}

Possible to add option to export UI component separately ?

Hey !
Thanks for your work on this cool module.

I'm trying to run some tests on a dumb component that is used to render the LoadingBar.

I can't run tests on the UI part only as I can't import it separately because you're connecting to the store in the loading bar file and exporting the container.

Would it be possible to split the logic of connecting to store and rendering, and therefore allowing the user the option to import the smart connected component or the ui component and manage state herself ?

Leaving the connected as a default makes complete sense, it would just be cool to be able to import the dumb component.

Happy to submit a PR if you're interested !

Cheers !

Redux 4.x.x support in package.json

There was a new major version of Redux released recently Changelog. At first look it doesn't appear to contain any breaking changes. Any chance of updating the dependency in package.json to "redux": ">3.5.2"?

Handle fast request

Hi,

I'm using your module for my API request and I'm facing a problem right now. Often the request are very fast - let's say 5 ms (right now the server is running on localhost). For those request you want even the see the loading bar.

I would appreciate to see the bar quickly moving towards 100% and then disappearing. I guess this can be easily implemented by just adding a property "transitionTime" or something similar. So if the hide function is triggered, it sets the loading width to 100% while slowly disappearing.

For testing this behaviour, you could just call show() and hide() directly behind each other. The users should see something - if it's only for a very short timespan.

Right now I'm trying to add a nice feature to your loading bar for my project. If the server request was successful the bar should become green shortly before disappearing. Otherwise it becomes red - maybe it doesn't disappear directly.

Example for a nice implementation: http://chieffancypants.github.io/angular-loading-bar/#

Thank you for your work,
Thomas

simulateProgress will still clearInterval when loadingbar > 0

1 put(showLoading())
2 put(hideLoading())
3 put(showLoading())
4 put(hideLoading())
if 2 is very closely to 3, simulateProgress will ingnore the loadingbar state, and disappear the loading bar .

I solve the problem in this way:

componentWillReceiveProps(nextProps){
    if (this.shouldStart(nextProps)) {
        this.launch();
    } else if (this.shouldStop(nextProps)) {
        this.setState({ percent: this.props.maxProgress });
    }
}

simulateProgress() {
    let { progressInterval, percent, endingAnimationTimeout } = this.state
    const { maxProgress } = this.props

    if (percent === this.props.maxProgress && this.props.loading === 0) {
      clearInterval(progressInterval)
      endingAnimationTimeout = setTimeout(
        this.boundResetProgress,
        ANIMATION_TIME,
      )
      percent = 100
      progressInterval = null
    } else if (this.newPercent() <= maxProgress) {
      percent = this.newPercent()
    }

    this.setState({ percent, progressInterval, endingAnimationTimeout })
  }

set background color via className

Now I see the only way to override background color is by setting style prop. But I would like to use className prop only and configure style in sass. To override background I have to use !important which makes my sass linter unhappy

More default CSS animation styles customization options

What do you think of adding multiple CSS transition or animation styles, like stripes?

I cannot seem to add such custom styles using classNames or inline styles easily without having to go and make changes to the following code.

const style = {
      opacity: '1',
      transform: `scaleX(${this.state.percent / 100})`,
      transformOrigin: 'left',
      transition: `transform ${animationTime}ms linear`,
      width: '100%',
      willChange: 'transform, opacity',
    }

    // Use default styling if there's no CSS class applied
    if (!this.props.className) {
      style.height = '3px'
      style.backgroundColor = 'red'
      style.position = 'absolute'
    }

Unallocated progressInterval handler

I basically perform the actions bellow:

  1. dispatch(showLoading())
  2. dispatch(hideLoading())
  3. dispatch(showLoading())
  4. dispatch(hideLoading())
    .....
    Sometimes the error bellow pops up in an infinite loop:
    window.console.error
    @ VM54:27printWarning
    @ warning.js:36warning
    @ warning.js:60
    getInternalInstanceReadyForUpdate
    @ ReactUpdateQueue.js:48enqueueSetState
    @ ReactUpdateQueue.js:200ReactComponent.setState
    @ ReactComponent.js:64resetProgress
    @ loading_bar.js:104

I think that the resetProgress() from the 2) dispatch gets called after launch() function from 3) dispatch which overrides this.state.progressInterval.

A workaround/fix I did was to modify resetProgress:
resetProgress() {
if (this.state.progressInterval) {
clearInterval(this.state.progressInterval);
}
this.setState(initialState);
}

Usage of `dispatch()`

Hi,

I'm trying to make use of the dispatch(showLoading()) in my actions, using redux-api-middleware in actions like this:

export function getClients(page = 1, count = 10) {
  return (dispatch, getState) => {
    const { auth: {oauthToken, oauthTokenSecret}} = getState();
    return dispatch({
      [CALL_API]: {
        endpoint: `/api/clients?page=${page}&count=${count}`,
        method: 'GET',
        headers: {
          'xoauthtoken': oauthToken,
          'xoauthtokensecret': oauthTokenSecret,
        },
        types: [GET_CLIENTS, GET_CLIENTS_SUCCESS, GET_CLIENTS_FAIL],
      }
    });
  }
}

I've managed to make it show but not hide, though, by putting right after the first return.

Upgrade to 2.9.0 caused loading bar to not appear in production builds of addons.mozilla.org

Howdy there!

Sorry for the issue with minimal info but I looked at what I think is the diff between 2.8.2...2.9.0 and couldn't find much that would indicate a breaking change.

But our production builds which include serving the site with these CSP rules:

default-src 'none'; base-uri 'self'; child-src 'none'; connect-src https://addons.mozilla.org https://sentry.prod.mozaws.net; form-action 'self'; frame-src 'none'; img-src 'self' data: https://addons.cdn.mozilla.net https://addons-amo.cdn.mozilla.net https://www.google-analytics.com; media-src 'none'; object-src 'none'; script-src https://addons-amo.cdn.mozilla.net https://www.google-analytics.com/analytics.js; style-src https://addons-amo.cdn.mozilla.net 'sha256-DiZjxuHvKi7pvUQCxCVyk1kAFJEUWe+jf6HWMI5agj4='; report-uri /__cspreport__; font-src https://addons-amo.cdn.mozilla.net

do not display the loading bar once updated to 2.9.0. Downgrading to 2.8.2 works fine. I can point you to our code usage if that would help, but I'm filing here because I'm a bit lost and I'm not sure why the loading bar stopped working.

mozilla/addons-frontend#2395

Loading Bar not displayed

Hi @mironov,

I am hoping you can help me solve an issue I am having with react-redux-loading-bar. I have installed the package and I created a component for <LoadingBar />. The component shows up when my app is loading (I can see my gradient overlay), however LoadingBar stays at opacity: 0; and transform: scaleX(0).

Here is my code...

LoadingBar component:

import React from 'react';
import styled from 'styled-components';
import { ImmutableLoadingBar as LoadingBar } from 'react-redux-loading-bar';
import {
  InfoColor,
} from '../constants';

// styles for progress bar wrap
const WrapProgressBar = styled.div`
  width: 100%;
  height: 10px;
  position: absolute;
  top: 0;
  left: 0;

  header, header > div {
    width: 100%;
  }
`;

// styles for gradient overlay
const GradientOverlay = styled.div`
  background: rgba(57,56,54,0.8);
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 99999;
`;

const ProgressBar = ({ fetching }) => (
  <WrapProgressBar fetching={fetching}>
    <header>
      <LoadingBar style={{ backgroundColor: InfoColor, height: '10px', opacity: '1', zIndex: '100000' }} />
    </header>
    <GradientOverlay />
  </WrapProgressBar>
);

export default ProgressBar;

Added reducer to store:

const appReducer = combineReducers({
    route: routeReducer,
    language: languageProviderReducer,
    loadingBar: loadingBarReducer,
    form,
    ...injectedReducers,
  });

Apply middleware:

const store = createStore(
    createReducer(),
    fromJS(initialState),
    composeEnhancers(...enhancers),
    applyMiddleware(loadingBarMiddleware())
  );

LoadingBar component in app:
{fetching && <ProgressBar fetching={fetching} />}

Any help is appreciated. Thank you!

Cannot read property 'default' of undefined

Warning: performUpdateIfNecessary: Unexpected batch number (current 2, pending 1)

connectAdvanced.js?4805:241 Uncaught TypeError: Cannot read property 'default' of undefined
Function.mapStateToProps [as mapToProps] (loading_bar.js?3859:250)

Try add redux loading bar and have this error

My reducer

import { combineReducers } from 'redux-immutable';
import { routerReducer as router } from 'react-router-redux';

import { loadingBarReducer } from 'react-redux-loading-bar'
export default combineReducers({

  router,
  ProtectedReducer,
  loadingBar: loadingBarReducer,

});

How I add

import LoadingBar from 'react-redux-loading-bar'
import { ImmutableLoadingBar as LoadingBar } from 'react-redux-loading-bar' - not helps to
and in render I add <LoadingBar  />

TypeDefinition support? [help wanted]

I'm currently using typescript to write my react app, therefore I need to have the TypeDefinition file for this library so that I can use it.
Are contributors going to write one for it?

Event loading-bar/SHOW is being triggered but the component still hidden

I'm trying to use this component but for some reason it looks like the component is not reacting to the state, the events are triggered but the bar doesn't shows up.. I'm using version 2.9.0 btw and react 15.5.4...

my setup:

const middleware = applyMiddleware(
    routerMiddleware(history),
    promise(),
    thunk,
    loadingBarMiddleware(),
    createLogger()
);
const store = createStore(
    combineReducers({
       ...
        loadingBar,
        router
    }),
    middleware
);

...

ReactDOM.render(
    (
        <Provider store={store}>
            <ConnectedRouter history={history}>
                <div id="app">
                    <LoadingBar showFastActions className="progress-bar"/>
                    ...
                </div>
            </ConnectedRouter>
        </Provider>
    ),
    document.getElementById('root')
);

UPDATE:

not even with saga and triggering the events manually it doesn't seems to work.

Creating an optimized production build... Failed to compile. after update to 4.0.2

I am using Create-react-app to build my app, but after I update my react-redux-loading-bar package to 4.0.2 version I got error below:

Creating an optimized production build...
Failed to compile.

Failed to minify the code from this file:

    ./node_modules/react-lifecycles-compat/react-lifecycles-compat.es.js:64

Read more here: http://bit.ly/2tRViJ9

I am guessing if I downgrade my version to 4.0.0 it will work but I didn't test it yet.

Is this supposed to work with server-side rendering?

I get this exception

Warning: setState(...): Can only update a mounting component. This usually means you called setState() outside componentWillMount() on the server. This is a no-op. Please check the code for the LoadingBar component.

Thanks

Not sure if shouldShow is neccecary

For my personal use I found that if a page loaded really quickly and say percent was only at 30% when I called hideLoading() then the loading bar would fade out too quick before reaching the end and giving an appearance of it just disappearing.

Since width of the bar is tied to loading percentage (and wont be visible when loading = 0 in the redux store) I removed the shouldShow section from your render method so its just const style = this.buildStyle() before returning and now it behaves properly and animates to end before disappearing (width gets set to 0) when percent gets set to 100 via hideLoading().

I thought perhaps the shouldShow is intentional for use cases unlike mine but thought I'd let you know. Cheers.

EDIT: Oops. Just realised removing it completely causes the animation back to 0 to be visible. This achieves what I was after:

        const shouldShow = this.props.loading > 0 || this.props.loading == 0 &&  this.state.percent > 0
        if (shouldShow) {
            style.opacity = '1'
        } else {
            style.opacity = '0'
        }

loading bar not display

Hi,

I tried all of your description, but, the loading bar is not display. Do I need any css file or so? Please need your help.

Thanks,

error in isomorphic app

/Users/admin/WebstormProjects/chefmarket/node_modules/fbjs/lib/invariant.js:38
error = new Error(format.replace(/%s/g, function () {
^
Invariant Violation: React DOM tree root should always have a node reference.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.