0
useEffect(() => {
    getAllCompanies()
      .then((response) => {
         //setting
      })
      .then(
         setSearch(value)
       )
      .then(
         doSomethingWith(value)
      )

  }, []);

I have an useEffect where I get Info and then with setSearch() I am setting some info to state but when I call doSomethingWith(value) it is using previous state and doesn't work asynchroniosly. What can I do?


If you have some questions please comment

Albert Margaryan
  • 57
  • 1
  • 2
  • 8
  • Setting state is not immediate. Related: [Why calling react setState method doesn't mutate the state immediately?](https://stackoverflow.com/questions/30782948/why-calling-react-setstate-method-doesnt-mutate-the-state-immediately) – crashmstr Dec 02 '20 at 13:38
  • I know it I just wanted to know to make it async – Albert Margaryan Dec 02 '20 at 13:43
  • "keep" the value in a local-ish scope variable for re-use within the same context or `useEffect` on the state variable. – crashmstr Dec 02 '20 at 13:47

2 Answers2

2

You have to use 2 useEffects to accomplish this.

The first useEffect will run only once when the component initially renders because it's not watching any state changes(given in an empty array).

The second useEffect will run every time when the "value" changes(it is watching for all changes in the value).

useEffect(() => {
    getAllCompanies()
      .then((response) => {
         //setting
      })
      .then(
         setSearch(value)
       )
  }, []);
  
  
  useEffect(() => {
      doSomething(value)
  }, [value]);
Amir Suhail
  • 81
  • 1
  • 6
0

Try this:

useEffect(async () => {
    await searchSet();
    let response = await getAllCompanies()
    // Your return value from function
    await setSearch(value)
    doSomethingWith(value)
}, []);

Or you can try this:

useEffect(() => {
    setTimeOut(() => {
        searchSet();
        setTimeOut(() => {
           let value = getAllCompanies();
           setTimeOut(() => {
               setSearch(value);
               setTimeOut(() => {
          doSomethingWith(value);
               }, 0);
           }, 0);
        }, 0);
    }, 0);
}, []);

Explanation:

1. async await

by using async before parentheses () and using await in function can hold your code till the code on that line completely executed.
Once code executed it moves to next line of code.

2. setTimeOut

By using setTimeOut() function with 2nd arguments as 0 does the same.
It runs after the upper line of code is completely executed.

MrJadeja
  • 441
  • 2
  • 8