0

I am making a request like this:

    const createProgramari = async () => {
        let prog = [];
        try {
            await axios.get('http://localhost:8000/api/programariByDentistID', {
                params: {
                    id: JSON.parse(localStorage.getItem('user'))["id"]
                }
            })
                .then(function (res) {
                    console.log(res);
                    if(res.status === 200) {
                        prog = res.data;
                    }
                })
                .catch(function (error) {
                    console.log(error);
                });
            setProgramari(prog);
        } catch(e) {
            console.log(e);
        }
    }

If I try to see this in my useEffect the variable 'programari' is an empty array (the value I initialized it with)

    const [programari, setProgramari] = useState([]);

    useEffect( () => {
        // code to run on component mount
        createProgramari();
        console.log(programari);
    }, [])

I tried printing the response and axios gets it right. What am I doing wrong? Is there a place I could learn how to not do the same mistake?

3
  • 2
    setProgramari(prog) belongs inside the .then block Commented May 21, 2021 at 18:09
  • I also tried this before, but it was to no avail. Commented May 21, 2021 at 18:11
  • I just realized that your code doesn't make a lot of sense. Either use async/await, or you use .then callback. Only one of them at a time makes sense Commented May 21, 2021 at 18:15

4 Answers 4

3

The salient point here is that setProgramari is async in nature. If it is called, it doesn't necessarily imply that it will be executed right away. One way you can handle this is follows.


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

// consider useMemo or useCallback based on your use case if need be
useEffect(() => {
  // whatever logic you want to have
  console.log(programari); // will get new value always
}, [programari])
Sign up to request clarification or add additional context in comments.

7 Comments

This works. At first I get '[]' and after logging I get the values I need. Why does it work this way, though? Isn't there a way to 'collect' all the data you need when the component mounts without having a second useEffect?
Can you tell me what you intend to do once you get the new state. That would help a lot answer it @OldDew
I want to pull some appointment data from my database to fill a calendar
I think in that case having a useEffect for the same will make more sense.
programariByDentistID is appointment-data in my language, but I got the idea! Thank you!
|
1

The way you wrote the function is very confusing, I'd suggest refactoring this to

const createProgramari = async () => {
    try {
        const prog = (await axios.get('http://localhost:8000/api/programariByDentistID', {
            params: {
                id: JSON.parse(localStorage.getItem('user'))["id"]
            }
        })).data;
        setProgramari(prog);
    } catch (e) {
        console.log(e)
    }
}

Comments

0

To view data you can do something like this:

useEffect(() => {
   createProgramari()
     .then((someReturnedDataFromAPI) => { // Promise returned
       console.log(programari)
     })
 }, []) // Initialization

Comments

0

in useEffect programari is equal with [] because setProgramari() not update already existed state in current component version, if set new state for programari, this modification propagate rerendering component

console.log(programari) work with current component state version

if you want dump programari you can move console.log outsite useEffect in this case you get in console two dump - [] for first version and [ withData ] for version what rerender because setState()

or if you want use data from axios in useEffect you can return it how promise

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.