Amit
Amit

Reputation: 213

How to an update an api call after an action is dispatched with a dependant value which is updated

I have the following App.js:

  constructor(props) {
    super(props);
    this.props.setLoading();
  }

  componentDidMount(){
    this.convert();
  }

  changeFromCurr = (event) => {
    this.props.setFromCurrency(event.target.value);
    this.convert();
  }

  changeToCurr = (event) => {
    this.props.setToCurrency(event.target.value);
    this.convert();
  }

  changeAmount = (event) => {
    this.props.setValue(event.target.value);
  }

  convert = () => {
    return this.props.convertCurr(this.props.fromCurrency,this.props.toCurrency,this.props.value);
  }

  render() {
    const {fromCurrency, toCurrency, value, result} = this.props;
    return (
      <div>
        <CurrencyForm
          fromCurrency={fromCurrency}
          toCurrency={toCurrency}
          amount={value}
          changeFromCurr={this.changeFromCurr}
          changeToCurr={this.changeToCurr}
          changeAmount={this.changeAmount}
          result={result}
        />

My Request is for convertCurr is:

mport convertCurrency from '../service';
import {requestApi, receiveRes, accessDenied, apiError} from './currencyActions';

function convertCurr(from,to,amt) {
    return dispatch => {
        dispatch(requestApi());
        convertCurrency(from,to,amt)
        .then(res => res)
        .then(res => {
            if(res.error) {
                throw(res.error);
            }else if(res.accessDenied){
                dispatch(accessDenied(res.accessDenied));
            }
            dispatch(receiveRes(res.data.rates[to]));
            return res.result;
        })
        .catch(error => {
            dispatch(apiError(error));
        })
    }
}

Which calls this service :

import axios from 'axios';


let convertCurrency = async (from,to,amt) => {
    const API_KEY= `b688884ff57c3e17139e632b5f852755`;
    const convertUrl = `http://data.fixer.io/api/latest?
    access_key=${API_KEY}&base=${from}&symbols=${to}`
  try {
    const response = await axios.get(convertUrl);
    console.log(response);
    return response;
  }
  catch (err) {
    console.log('fetch failed', err);
  }
}

export default convertCurrency;

Now What I want to do is fire this service call once my Redux store gets updated with new fromCurrency property after the:

this.props.setFromCurrency(event.target.value);

updates the state, I want the service to be called with new values. Any help would be much appreciated.

Upvotes: 0

Views: 40

Answers (1)

keikai
keikai

Reputation: 15146

Use react life-cycle componentDidUpdate

componentDidUpdate(prevProps, prevState) {
  if (yourMethodToCheckIfNotEqual(prevProps.fromCurrency, this.props.fromCurrency)) {
    // Fire your service call
    // Notice that if your service call changes fromCurrency above may cause infinite loop
  }
}

Upvotes: 1

Related Questions