0

So decided to use redux-thunk and I have a problem to write a function in my actions and reducer. Actually function looks like this:

  async getData() {
    if (this.props.amount === isNaN) {
      return;
    } else {
      try {
        await fetch(
          `https://api.exchangeratesapi.io/latest?base=${this.props.base}`,
        )
          .then(res => res.json())
          .then(data => {
            const date = data.date;
            const result = (data.rates[this.props.convertTo] * this.props.amount).toFixed(4);
            this.setState({
              result,
              date,
            });
          }, 3000);
      } catch (e) {
        console.log('error', e);
      }
    }
  }

Also I already have action types

export const FETCH_DATA_BEGIN = 'FETCH_DATA_BEGIN';
export const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
export const FETCH_DATA_FAIL = 'FETCH_DATA_FAIL';

and actions like this

export const fetchDataBegin = () => {
  return {
    type: actionTypes.FETCH_DATA_BEGIN,
  };
};

export const fetchDataSuccess = data => {
  return {
    type: actionTypes.FETCH_DATA_SUCCESS,
    data: data,
  };
};

export const fetchDataFail = error => {
  return {
    type: actionTypes.FETCH_DATA_FAIL,
    error: error,
  };
};

And then comes the hard part for me where I don't know how to get the same result from function async getData(). I already have just this in my action :

export async function fetchData() {
  return async dispatch => {
    return await fetch(`https://api.exchangeratesapi.io/latest?base=${this.props.base}`)
        .then(res => res.json())
        .then(data => {
         // <------------------- WHAT NEXT?
  }
};
Aphrem Thomas
  • 215
  • 1
  • 7

1 Answers1

2
export function fetchData() {
  return dispatch => {
    fetch(`https://api.exchangeratesapi.io/latest?base=${this.props.base}`)
        .then(res => res.json())
        .then(data => dispatch(fetchDataSuccess(data)), e => dispatch(fetchDataFail(e)))
  }
};

Now this code:

const date = data.date;
const result = (data.rates[this.props.convertTo] * this.props.amount).toFixed(4);
this.setState({
  result,
  date,
});

goes into your reducer

if(action.type === FETCH_DATA_SUCCESS) {
  const date = action.data.date;
  const rates = action.data.rates;
  return { ...state, rates, date };
}

Now you can use the redux state in your component and make the rest of the calculations there (ones that need this.props).

To dispatch the fetchData action now, you do this.props.dispatch(fetchData()) in your react-redux connected component.

EDIT

Here's how you use the state in the component.

I'm assuming you have created the redux store. something like:

const store = createStore(rootReducer,applyMiddleware(thunk));

Now, you can use the react-redux library's connect function to connect the redux state to your component.

function mapStateToProps(state, ownProps) {
  return { 
    date: state.date,
    result: (state.rates[ownProps.convertTo] * ownProps.amount).toFixed(4);
  }
}

function mapDispatchToProps(dispatch) {
  return {
    fetchData: () => dispatch(fetchData())
  }
}

export default connect(mapStateToProps,mapDispatchToProps)(YourComponent)

You can use this Higher Order Component in your DOM now and pass the appropriate props to it:

import ConnectedComponent from "./pathTo/ConnectedComponent";
...
return <View><ConnectedComponent convertTo={...} amount={...} /></View>;

And, also inside YourComponent you can now read this.props.date and this.props.result and use them wherever you need to.

You might want to look at selectors in the future to memoize the state and reduce the performance cost of redux.

marc_s
  • 675,133
  • 158
  • 1,253
  • 1,388
giotskhada
  • 1,600
  • 1
  • 7
  • 16
  • Can u also write how to use redux state in component to do those calculations? – Daniel Gola Mar 06 '20 at 02:52
  • Sure thing! Sorry, it was nighttime where I live, had to go. I'll edit the answer and show the state usage code – giotskhada Mar 06 '20 at 09:55
  • Thank you very much Giorgi! Can I ask you about similar problems in future? It looks you have knowlage about that ;) – Daniel Gola Mar 06 '20 at 12:38
  • You're welcome! I'd love to help anyone who needs it, whenever I can find time. – giotskhada Mar 06 '20 at 12:49
  • Well I did what u wrote to me and it almost work! Now i have NaN problem. Have u time to help me figure this out? – Daniel Gola Mar 06 '20 at 13:29
  • I'll be off work in about two hours, so go ahead and add a new question with details and I'll check it out later, if anyone else doesn't answer first. – giotskhada Mar 06 '20 at 13:38
  • So when you got some time check here if there would be no asnwer: https://stackoverflow.com/questions/60565762/nan-problem-with-react-redux-and-react-thunk – Daniel Gola Mar 06 '20 at 14:10