How to correctly assign axios response to react function component state

11,006

Solution 1

Make the axios request inside the useEffect hook, in order to run once the component is mounted.

import { useEffect } from 'react';

const Translator = () => {
    const [languages, setLanguages] = useState([]);
    useEffect(() => {
      getLanguages().then(data => {
         setLanguages(data.languages)
      });

      console.log(languages);
    }, []);
    
  
  return (
    <header className="translator__header">
        {
          languages.length > 0 && (
            languages.map( lang => <h1>{lang.language}</h1>)
          )
        }
    </header>
  );
};

Solution 2

It's giving you the infinite loop, because you're changing state on each render. Put this code in useEffect hook

getLanguages().then(data => {
   setLanguages(data.languages)
});

Solution 3

Try to use the useEffect hook. Passing [] as the second argument is closer to the familiar componentDidMount and componentWillUnmount mental model.

In React, when you use lists, each list item needs a unique key.

const Translator = () => {
    const [languages, setLanguages] = useState([]);

    useEffect(() => {
        getLanguages().then(data => {
           setLanguages(data.languages)
        });
    }, []);

    console.log(languages);
  
    return (
        <header className="translator__header">
            {languages.map(lang => {
                <h1 key={lang.language}>
                    {lang.language}
                </h1>
            })}
        </header>
    );
};
Share:
11,006

Related videos on Youtube

programmer
Author by

programmer

Updated on May 30, 2022

Comments

  • programmer
    programmer almost 2 years

    I have problem as in title. My code give me an infinite loop - the console log is looping all time.

    I just want to assign axios response to component state nad render elements via .map()

    component:

    const Translator = () => {
        const [languages, setLanguages] = useState([]);
        getLanguages().then(data => {
           setLanguages(data.languages)
        });
        
        console.log(languages);
      
      return (
        <header className="translator__header">
            {languages.map( lang => {
                <h1>{lang.language}</h1>
            })}
        </header>
      );
    };
    

    resource:

    export default () => {
        return Axios.get(`${config.baseURL}/languages`, {headers: config.headers}).then(res => {
            return res.data.data;
        });
    }
    

    request give array with object like this

    {language: "af"}
    
    • jonrsharpe
      jonrsharpe almost 4 years
      Please read up on useEffect.
    • programmer
      programmer almost 4 years
      @jonrsharpe Same situation
    • jonrsharpe
      jonrsharpe almost 4 years
      What is? Give a minimal reproducible example.
    • programmer
      programmer almost 4 years
      Look answer made by @Dyarlen my code now looking like this, but have another problem right now
  • programmer
    programmer almost 4 years
    Nothing happend :/
  • programmer
    programmer almost 4 years
    I put this into useEffect and still working in the same way :/
  • programmer
    programmer almost 4 years
    with useEffect like u - looping stop. I added a key, and now element are not showing
  • programmer
    programmer almost 4 years
    Look answer made by @Dyarlen - my code looking like this
  • Robert Sidzinka
    Robert Sidzinka almost 4 years
    This should work well, because the deps array is empty, to it should run only once. You're still getting infinite console.logs?
  • programmer
    programmer almost 4 years
    I thing the map() is creating elements before set data to state, but how can I figure out this?
  • programmer
    programmer almost 4 years
    look comments in @Dyarlen answer - there I explain what problem is now
  • Francisco
    Francisco almost 4 years
    Sorry @programmer I forgot to pass an empty array as a second argument. Try it and tell me if it works
  • programmer
    programmer almost 4 years
    works, but now elements are not rendering. I think there is problem cuz map() creating element when the array it still empty. But i'm not sure ot this
  • programmer
    programmer almost 4 years
    i put log inside map() and everything is right - objects shows in console, but still not rendered into DOM
  • Francisco
    Francisco almost 4 years
    @programmer I edited the code with a conditional if the length is grater than 1 then, it render the h1
  • programmer
    programmer almost 4 years
    Okay, nobody saw that I didnt put the return state to map() LOL. Sorry for my fault
  • Dyarlen Iber
    Dyarlen Iber almost 4 years
    @programmer What is the content of the language? Does every language property have a unique value?