Ben
Ben

Reputation: 16669

Integrating Pull-To-Refresh in a ScrollView with Redux in React Native

I am trying to add pull-to-refresh functionality to a <ScrollView> using a refreshControl and integrate it with Redux.

Example from https://facebook.github.io/react-native/docs/refreshcontrol:

_onRefresh = () => {
    this.setState({refreshing: true});
    fetchData().then(() => {
      this.setState({refreshing: false});
    });
}

My problem is that my own fetchData function dispatches an action for the reducer to handle, so as far as I understand it, it is not a thenable promise. So I don't fully understand the integration with Redux in this case. What do I need to change in my code to be able to set refreshing to false as in the above example?


PostFeedScreen.js

// on mount, fetch all posts from the API
componentDidMount() {
    this.props.fetchPostsFromAPI();
}

_onRefresh = () => {
    this.setState( { refreshing: true } );
    this.props.fetchPostsFromAPI().then( () => { // error
        this.setState( { refreshing: false } );
    });
}

// map dispatch to props
const mapDispatchToProps = ( dispatch ) => {
    return {
        fetchPostsFromAPI: () => {
            dispatch( fetchPostsFromAPI() );
        }
    }
}

PostActions.js

// fetch all posts
export function fetchPostsFromAPI() {
    return( dispatch ) => {
        let loadData = new Promise( ( resolve, reject ) => {
            resolve( postsInitial ); // using dummy data for now
        })
        loadData
            .then( posts => dispatch( fetchPostsSuccess( posts ) ) );
}

// is used if posts were succesfully loaded
function fetchPostsSuccess( posts ) {  
    return {
        type: PostConstants.FETCH_POSTS_SUCCESS,
        data: posts,
    }
}

PostReducer.js

const PostReducer = ( state = initialState, action ) => {

    switch( action.type ) {

        // if fetching data was successful
        case PostConstants.FETCH_POSTS_SUCCESS: {
            return {
                ...state,
                posts: action.data,
            }
        }

        default: {
            return state
        }
}

Upvotes: 1

Views: 938

Answers (1)

EQuimper
EQuimper

Reputation: 5929

You get an error cause you call .then on something who don't return a promises. Just add return in front of your loadData, cause you can chain promises.

export function fetchPostsFromAPI() {
  return dispatch => {
    let loadData = new Promise((resolve, reject) => {
      resolve(postsInitial);
    });

    return loadData.then(posts => dispatch(fetchPostsSuccess(posts)))
  };
}

Upvotes: 1

Related Questions