`How to call a function only after updating the state in useEffect?
L
L
lexstile2021-01-14 19:15:06
React
lexstile, 2021-01-14 19:15:06

How to call a function only after updating the state in useEffect?

There is a code:

const [filters, setFilters] = useState({});

  const filterByRedColor = () => {
    const apiUrl = `/api/?colorId=${filters.colors.red}`;
    callApi(apiUrl);
  };

  useEffect(() => {
    const asyncData = async () => {
      const data = await getFilters();
      setFilters(data);
      filterByRedColor(); // при добавлении 2-го useEffect эту строку убираю
    };
    asyncData();
  }, []);

Inside filterByRedColor , state is used . But when you first open the page there is an empty object and the application crashes.
What's the best way to get out?
I try by adding another effect:
useEffect(() => {
    Object.keys(filters).length && filterByRedColor();
  }, [filters]);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
glazzkoff, 2021-01-14
@lexstile

You can simply pass data to function parameters:

const [filters, setFilters] = useState({});

  const filterByRedColor = (data) => {
    const apiUrl = `/api/?colorId=${data.colors.red}`;
    callApi(apiUrl);
  };

  useEffect(() => {
    const asyncData = async () => {
      const data = await getFilters();
      setFilters(data);
      filterByRedColor(data);
    };
    asyncData();
  }, []);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question