Search code examples
react-nativereact-reduxfetchdispatch

React Native, Fetch, and Dispatch: How do I access responseData within mapDispatchToProps()?


I'm fetching JSON Data within componentWillMount() from my "Scanner" component like so:

async componentWillMount() {
  const url = 'https://foo.com/products/product1.json';

  fetch(url)
  .then((response) => response.json())
  .then((responseData) => this.props.dispatchProductLoad())
  .catch(error => {
    console.log(error);
  });
}

And below is my dispatch code:

function mapDispatchToProps(dispatch) {
  return { dispatchProductLoad: () => dispatch(productLoad(SOMEDATA)) };
};

export default connect(null, mapDispatchToProps)(Scanner);

Where the variable SOMEDATA should hold the value from responseData (at the moment it's not defined)

So my question is - how do I set the value of SOMEDATA to the value held in responseData?


Solution

  • You would call the action creator with the responseData as an argument and define your mapDispatchToProps function like

    async componentWillMount() {
      const url = 'https://foo.com/products/product1.json';
    
      fetch(url)
      .then((response) => response.json())
      .then((responseData) => this.props.dispatchProductLoad(responseData))
      .catch(error => {
        console.log(error);
      });
    }
    
    
    function mapDispatchToProps(dispatch) {
      return { dispatchProductLoad: (response) => dispatch(productLoad(response)) };
    };
    
    export default connect(null, mapDispatchToProps)(Scanner);