Answer the question
In order to leave comments, you need to log in
`
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();
}, []);
useEffect(() => {
Object.keys(filters).length && filterByRedColor();
}, [filters]);
Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question