Albert Margaryan
Albert Margaryan

Reputation: 97

React js useEffect

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

Upvotes: 0

Views: 78

Answers (2)

MrJadeja
MrJadeja

Reputation: 451

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.

Upvotes: 0

Amir Suhail
Amir Suhail

Reputation: 81

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]);

Upvotes: 2

Related Questions