two-way `useEffect` to fetch Currency exchange rate from API implementation not working.
I have a currency converter website which fetches currency values from an API. The value for the two input boxes is taken from 2 states
Now i want the useEffect to fetch currency rate from the API whose response is of the format
I want the value of state 2 to change when state 1 value is set by the user and vice-versa, based on the currency rate 'value' fetched from the API.
The axios GET request is as follows:
How do i write the useeffect to fetch according to my requirements
20 Replies
Just that I understand your problem correctly:
- you got your request
- you got your state
and your question is how to get the response out of axios and into setState inside an useEffect?
yes
But it should work both ways. i.e: the api request is triggered when the user changes any one of the inputs. i.e. the state value of either state1 or state2 changes.
So if user changes state1, the useEffect will update the state2 value to the converted value.
You may want to use two useEffects, one for each of the states, that sets the other.
getCourse
would be the function, which gets the value (I omitted await for simplicity sake)I tried this out. There is an issue
The input value to state1 triggers a rerender so the state 2 value does not even change, and the state1 value itself does not change
it goes into an infinite loop.
Yeah using two
useEffect
s like that will send you into an infinite loop. Since you said it would be triggered when the user changes the values, maybe trying updating the state withing the handleChange
functions for the inputs? So when the user updates the input form for state1
, you make an API request for the conversion then update state2
, and vice versaLet me see if I understood correctly.
What you are trying to say is to instead of making use of a
useEffect
hook, incorporate the API call within the handleChange
function that changes the input values of both state1
and state2
when triggered by the user.Yeah, so when the user updates the
input
that has state1.value
, you update state1
to whatever the user inputs, then send the API request. No clue if it's the best way of doing things tho
¯\_(ツ)_/¯I will give it a try
I tried that. It doesnt work as expected
state2 value is changed before API response arrives. This delay will cause the setState2 to set value to be
NaN
.Are you
await
ing the API response?yes
Can you share your
handleChange
code for one of the inputs?
I have used a single function to do change both the input values
You aren't making the API calls to update the state here
oh the updated one?
hold on
This is what i tried
the fetchCurrencyRate is an async function
You have to
await
the result of fetchCurrencyRate
then
So handleChange
will have to be async as welloh i see
BRUH....
it worked
🥳
This is the final function
I think I now just have to add the same logic in the else part of the loop