Search code examples
javascriptreactjstypescriptif-statementfrontend

How to implement nested if else and using SetState in react js


I have following code:

const Stepper = (id) => {
  let currId = id;
  const steps = [
    "Event Information",
    "Agenda & Schecule",
    "Budget Information",
    "Registration Attendee",
  ];
  const [currentStep, setCurrentStep] = useState(1);
  const [selectorCard, setSelectorCard] = useState(0);
  const [isStatus, setStatus] = useState("");
  const [complete, setComplete] = useState(false);

  const checkData = (id) => {
    if (id === "0") {
      setSelectorCard(0);
      setCurrentStep(1);
      () => setStatus("Pending");
    } else if (id === "1") {
      setSelectorCard(1);
      setCurrentStep(2);
      setStatus("Client Negotiation Approved");
    } else if (id === "2") {
      setSelectorCard(0);
      setCurrentStep(1);
      setStatus("Client Negotiation Rejected");
    } else if (id === "3") {
      setSelectorCard(2);
      setCurrentStep(3);
      setStatus("Agenda Schedule Approve");
    } else if (id === "4") {
      setSelectorCard(1);
      setCurrentStep(2);
      setStatus("Agenda Schedule Revision");
    } else if (id === "5") {
      setSelectorCard(3);
      setCurrentStep(4);
      setStatus("Event Budget Approved");
    } else if (id === "6") {
      setSelectorCard(2);
      setCurrentStep(3);
      setStatus("Event Budget Revision");
    }
  };

  useEffect(() => {
    checkData(currId.Id);
    console.log(currId.Id);
    console.log(isStatus);
  }, []);

When i try to look at console.log it always bring null value, just a few conditions bring the correct value of setStatus() function. Please englight me about this.

I have search any reference about null value of setState


Solution

  • Is it possible that currId is empty when the component is initialized? If so, then the current approach is problematic, since you're trying to access currId in the useEffect without including it in the dependency array (so you have a stale closure).

    You can add it as follows:

      useEffect(() => {
        if(!currId.Id) { 
          return;
        }
        checkData(currId.Id);
        console.log(currId.Id);
        console.log(isStatus);
      }, [currId]);
    

    This way every time currId changes, the useEffect will run updating state accordingly

    Alternatively you can just put the id in the dep array:

      useEffect(() => {
        ...// same as above
      }, [currId.Id]);
    

    Which I'd say is probably the better approach if that's all you need to access in the useEffect, especially if currId is in fact an object with other potentially changing data