Андрей Гузюк
Андрей Гузюк

Reputation: 2164

How to load data if needed ? React / Redux. No SSR

Is it possible to load data if needed?

For example: first time I loaded list of challenges then I went to details page. Now I will refresh page and will get errors something like challenges undefined because calling api only when loading list of challenges.

So question is how to call api again only that time when store is empty?

Thanks!

Upvotes: 2

Views: 701

Answers (3)

Андрей Гузюк
Андрей Гузюк

Reputation: 2164

Thanks for answers, but solution's above not what i need.

So i achieved that with onEnter hook on Route.

Here is my approach:

export default function(store, history) {
    const requireChallenges = (nextState) => {
        if(!challengesIsLoaded(store.getState())) {
            store.dispatch(fetchChallenges());
        }
    };
    return (
            <Provider store={store}>
              <Router onUpdate={() => window.scrollTo(0, 0)} history={history}>
                <Route path="/challenges/" component={ChallengesScene} onEnter={requireChallenges} />
              </Router>
            </Provider>
);

Thanks!

Upvotes: 0

flocks
flocks

Reputation: 218

Just set your initialState's challenges attribute to null and check if the state.challenges if defined before calling the API.

For example:

constructor(props) {
    super(props);
    this.state = {challenges: null}
}
componentDidMount() {
    if (!this.state.challenges) {
        MyAPI.getChallenges().then(function(result) {
            this.setState({challenges: result.challenge});
        })
    }
}

Upvotes: 1

Vikram Saini
Vikram Saini

Reputation: 2771

you can set your state like this:

this.setState({
  challenges :data
});

When you navigate to details page then you can pass this as props to child components as:

render{
  return(
    <Details challenges={this.state.challenges }/>
  );
}

in details component you can access the data as

this.props.challenges

and store it inside a variable or your component state. This way you can always retain your data

Upvotes: 1

Related Questions