Home > Enterprise >  How to use multiple setState sequentially one after another in ReactJS
How to use multiple setState sequentially one after another in ReactJS

Time:08-27

I just got to know that setState is a async call.

I want to use the result updated by setState in a very next line but as it is a async call I am getting old result of state. I check lot of solutions but they are mostly class based react and I am using functional based component, class based component setState do have a second args which can be use as a callback but what about functional based?

How & how many approaches do we have to tackle this issue. here is my code, I want to use filtersAdded state result in a next line to update another state...

  const { data, setData } = useContext(defaultData);
  const [pestleFilters, setPestleFilters] = useState([]);
  const [filtersAdded, setFiltersAdded] = useState([]);
  let flag = 0;
  let availableFilters = [];
  const [toggleFilter, setToggleFilter] = useState(false);

  const addFilter = (val) => {
    let filters = [...filtersAdded];
    filters.push(val);
    setFiltersAdded(filters);
    let pestleFiltersAux = [...pestleFilters].filter((item) => {
      if (!filters.includes(item)) {
        return { item };
      }
    });
    setPestleFilters(pestleFiltersAux, () => {
      console.log(filtersAdded);
    });

    let temp = data.filter((d) => filtersAdded.includes(d.pestle));
    console.log(temp);
  };

CodePudding user response:

Why don't you use filters variable if it is equal to filtersAdded ?

let temp = data.filter((d) => filters.includes(d.pestle));
console.log(temp);

You can't access a state that you just set in the same function, one way you could do this is by creating a useEffect that listen to your state that you just set, like in the example below:

    const [state, setState] = useState(0)
const [otherState, setOtherState] = useState(0)

const func = () => {
  setState(3)
}

useEffect(() => {
  setOtherState(state   1)
}, [state])

Once you will call the func(), the state will be updated to 3 and useEffect will throw his function because it listen to "state", so otherState will be updated to 4.

  • Related