chickencoop
chickencoop

Reputation: 41

How come my state isn't being filled with response?

console.log(data) gives me an object with the correct data but, I set rates to that data but when console logging rates I get an empty object {}. Thanks in advance.

const [rates, setRates] = useState({});

  useEffect(() => {
    search();
  }, []);

  const search = async () => {
    const response = await axios.get('https://api.exchangeratesapi.io/latest');
    const data = response.data.rates;
    console.log(data);
    setRates(data);
    console.log(rates);
  };

Upvotes: 1

Views: 83

Answers (1)

Yatrix
Yatrix

Reputation: 13775

As someone said in the comment, state updates will be reflected in the next render. Also, there are some problems with your code I'll address.

  const [rates, setRates] = useState({});

  useEffect(() => {
      // move this in here unless you plan to call it elsewhere
      const search = async () => {
          const response = await axios.get('https://api.exchangeratesapi.io/latest');
          const data = response.data.rates;
          setRates(data);
       };
    search();

  }, [/* no dependencies means it runs once */]);

If you do plan on calling search elsewhere, wrap it in a useCallback hook so you can set it as a dependency of your useEffect (you'll get a lint warning without). useCallback with an empty dependency array will always return the same function reference, so your useEffect will only ever run the one time like it does now.

If you leave search as a normal function in the component, the reference changes each render, so your effect would run every render if you included it as a dependency.

 const [rates, setRates] = useState({});  
 const searchCallback = useCallback(async () => {
      const response = await axios.get('https://api.exchangeratesapi.io/latest');
      const data = response.data.rates;
      setRates(data);
  }, [])

 useEffect(() => {
      // move this in here unless you plan to call it elsewhere
      
    search();

 }, [searchCallback]);

Upvotes: 1

Related Questions