Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 553
Steve Avatar asked Jan 19 '26 17:01

Steve


1 Answers

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);
like image 167
Shubham Khatri Avatar answered Jan 21 '26 09:01

Shubham Khatri