简体   繁体   中英

Fill UseState with data from axios React JS

I cant get userData value out of axios function. Console says that userData is undefined but thats not the case. I guess it has something with async/await but I am not sure how to use it.

    var userData;

    async function getData() {
    const data = {
        KorisnickoIme: 'uros'
    };
    const url ='https://localhost:44357/api/Fin/ProfileSetUp';
        axios.post(url, data).then((result)=>{
            window.userData = result.data.split(";");
        }, []).catch((error)=>{
            alert(error);
        })
    }

    getData();
    console.log(window.userData);
    
    const [email, setEmail] = useState(window.userData[1]);

I am tried to treat userData as global variable but without any luck.

You're doing it backwards. Don't try to stop the component from rendering at all while you load asynchronous data. (That is... Don't try to use the result of the asynchronous operation to define the initial state.) Define the initial state of the component, then load the data to update that state.

For example, the initial state can be undefined :

const [email, setEmail] = useState();

or perhaps an empty string:

const [email, setEmail] = useState('');

or whatever value you like. Then define the operation which fetches data and updates state:

function getData() {
  const data = {
    KorisnickoIme: 'uros'
  };
  const url ='https://localhost:44357/api/Fin/ProfileSetUp';
  axios.post(url, data).then((result)=>{
    setEmail(result.data.split(";"));  // Use the setter to update React state
  }, []).catch((error)=>{
    alert(error);
  });
}

Then use useEffect to invoke that operation when the component first loads:

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

So the component will first render with the initial default state, then after the asynchronous operation completes it will re-render with the new updated state.

Note the empty dependency array passed to useEffect here. That would cause the operation to run once, when the component initially loads. Adding any values to the dependency array would cause the operation to run any time the component re-renders with changes to those values. Omitting the array entirely would cause the operation to run on every render (which you probably don't want in this case).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM