Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use multiple setState sequentially one after another in ReactJS

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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);
  };

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading