0

I am using Redux to create my pagination. My problem is, in constructor I ran a method that will parse the url and check if there is anything about pagination. Then it runs an action that will put the data in my store. It all runs smoothly.

Then, I have the componentDidMount method when I run another action - fetching data. And there I use those props I have previously pushed. Unfortunately, the store is at its initial state.

My (simplified) code:

class NewsList extends React.Component {
    constructor(props) {
        super(props);

        this.profile = document.getElementById('articles').getAttribute('data-profile');

        this.parseHash();
    }

    parseHash() {
        /* Method for parsing navigation hash
         ---------------------------------------- */
        const hash = window.location.hash.replace('#', '').split('&');

        const data = {
            page: 1,
            offset: 0
        };

        // hash parsing

        this.props.setPagination(data);
    }

    componentDidMount() {
        this.loadNews();
        // If I use
        // setTimeout(() => { this.loadNews(); })
        // it works, but I feel this is hack-ish
    }

    loadNews() {
        this.props.update({
            current:  {page: this.props.NewsListReducer.current.page, offset: this.props.NewsListReducer.current.offset},
            next:     {page: this.props.NewsListReducer.next.page, offset: this.props.NewsListReducer.next.offset}
        });
    }
}

When I console.log(this.props.NewsListReducer), I am getting undefined for both current and next object, but when I use Redux DevTools, the data is there. What can I do?

Tomek Buszewski
  • 7,659
  • 14
  • 67
  • 112

1 Answers1

0

It seems like there's some asynchronicity somewhere in there. You're probably using react-redux right? I think the asynchronicity comes from the connected component, as it uses setState when the store state has changed. setState schedules an asychronous state update.

Therefore this.props.NewsListReducer isn't up to date in componentDidMount().

I guess this.props.update is an action that will fetch the news, right? Why is it necessary that you provide the paging information from the component to it? E.g. with redux-thunk you can access the store state before dispatching an action. This could be your chance for reading the (up to date) paging information.

E.g.

export function fetchNews() {
  return (dispatch, getState) => {
    getState().NewsListReducer.current.page; // Up to date

    ...

    fetch(...).then(() =>
      dispatch({...}));
  }
}

Btw. it could be a good idea to not call your state *Reducer. It's the reducer managing the state, but the reducer isn't part of the state in that manner.

amann
  • 5,449
  • 4
  • 38
  • 46