Alexandr Stupak
Alexandr Stupak

Reputation: 65

Incorrect call an API

  const [clientIfFromSearchWebitel, setClientIfFromSearchWebitel] = useState(
    undefined
  );


    useEffect(() => {
    console.log('clientIfFromSearchWebitel', clientIfFromSearchWebitel);
    if (clientIfFromSearchWebitel && clientIfFromSearchWebitel !== undefined && clientIfFromSearchWebitel !== '') {

      axios
      .post('https://extapi.megabank.ua/dev/ops/api/v1/getEntity/CASES', {
        filters: [
          {
            comparison: 'eq',
            fieldName: 'client_id',
            fieldValue: clientIfFromSearchWebitel
              ? clientIfFromSearchWebitel
              : undefined,
            operation: 'OR',
          },
        ],
      })
      .then(data => setFilterData(data.data));
    }else {
      axios
      .post('https://extapi.megabank.ua/dev/ops/api/v1/getEntity/CASES', {
        filters: [],
      })
      .then(data => setFilterData(data.data));
    }

  }, [clientIfFromSearchWebitel])

enter image description here

I have a clientIfFromSearchWebitel state, and when the component first appears, this state is undefined, when the component is updated again, the value is written to it based on which the API should be called, but the API is called instead of 1 time - 2 times, due to the fact that the 1st once the state is undefined 2nd with a value, how can this situation be fixed?

Upvotes: 1

Views: 62

Answers (1)

Siva Kondapi Venkata
Siva Kondapi Venkata

Reputation: 11001

I think you are talking about https://reactjs.org/docs/hooks-faq.html#can-i-run-an-effect-only-on-updates

const fetchNow = useRef(false);

useEffect(() => {
  if (fetchNow.current) {
    // do fetch now -- your existing code
  }
});

Where ever you are doing setClientIfFromSearchWebitel() replace with fetchNow.current = true

This way you can avoid useState and having conditions in useEffect.

Upvotes: 1

Related Questions