简体   繁体   中英

Why my useState is not updating the value?

I have an useState that gets the value from DB:

const [checklist, setChecklist] = useState(undefined);

在此处输入图像描述

And I have this condition, that when happens, I would like to change the useState:

let newItems = [];
let newChecklist = {};

  if (project?.analysisData?.actionPlan == "no") {
    newItems = checklist?.items?.filter(
      (item) => item.conformityStatus !== "initial_status"
    );
    newChecklist = { ...checklist, items: newItems };
  }

Notice that the items were filtered.

在此处输入图像描述

And I'm trying to change the value from my useState with useEffect:

useEffect(() => {
    setChecklist(newChecklist);
  }, []);

But for some reason it's not changing.. Anyone can help me? Thank you so much!

I created a new useState:

const [changeChecklist, setChangeChecklist] = useState(true);

called a setTimeout, to force some "change" after the component Mount:

setTimeout(() => {
    setChangeChecklist(false);
  }, 550);

and called the useEffect with the change of my new useState:

let newItems = [];

  useEffect(() => {
    if (project?.analysisData?.actionPlan == "no") {
      newItems = checklist?.items?.filter(
        (item) => item.conformityStatus !== "initial_status"
      );
      setChecklist({ ...checklist, items: newItems });
    }
  }, [changeChecklist]);

Maybe its not the best solution, but it was the one that I figured out to solve my problem:)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM