A
A
Andrey Okhotnikov2020-11-25 15:57:06
React
Andrey Okhotnikov, 2020-11-25 15:57:06

Problem with useEffect?

I have a request to api when changing 3 parameters in the state, respectively, it is written something like this

useEffect(() => {тут запрос}, [param1, param2, param3])

Everything would be fine, but when the page is first loaded, when all 3 parameters are set in the state, the user effect works 3 times. How to avoid this and get rid of unnecessary requests at the first boot?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2020-11-25
@Seasle

Use an object.

const [params, setParams] = useState({
    name: "John",
    email: "[email protected]",
    age: 30
});

Example .

N
Nikita Gennadich, 2020-11-25
@Psychosynthesis

Add to the isFirstRender state, for example...

const [isFirstRender, setNotFirstRender] = useState(true);

useEffect(() => {
  if(isFirstRender) {
    // тут запрос
    setNotFirstRender(false);
  }
}, [param1, param2, param3, isFirstRender]);

But, in general, I would still look towards using a chain of promises, so that the parameters are set only as the last one is received, this would be a more beautiful solution (IMHO).
Something like:
useEffect(() => {
  Promise1.then(() => { // первый параметр
    Promise2.then(() => { // второй
      Promise3.then(() => { // третий
      }
    }
  });
}, [param1, param2, param3]);

Although there are too many promises, the design is also so-so ... If I were you, I would think about where you can improve the architecture.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question