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!
CodePudding user response:
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 :)
CodePudding user response:
Can be many things, like:
1 - Are you sure 'if' conditions are true?
2 - So, checklist state is a object and has a 'items' key?
3 - checklist.items is an array?
4 - Console has some error?
I can't see any error in this code, so i assume the error is before, maybe when you set checklist value.