0

I am new to react and facing issues in updating the boolean state variable in functional components. I have highlighted the code

Sample code is here, I dont know what I am doing wrong here

const[child, setChild] = useState<Child>();
const[parent, setParent] = useState<Parent>();
const[hasChild, setHasChild] = useState<boolean>(false);

useEffect(() => {
    const getInformation = async () => {
      const response = await fetch(
        'http://localhost:8080/randomUrl/parameter/id',
        requestOptions
      );
      if (!response.ok) {
        throw new Error("Data coud not be fetched!");
      } else {
        return response.json();
      }
    };
    
     getInformation()
      .then((response) => {
        setParent(response);
        setChild(response?.child);
        initialize(response);
      })
      .catch((e) => {
        console.log(e.message);
      });
 }, []);

const initialize = (parent: Parent) => {
    if (parent?.child) {
      **setIsCurrentSector(UtilService.hasChild(parent?.child?.status)); // this should be true**
      **alert(isCurrentSector); // returning false always**
    }
}

UtilService

const hasChild = (status: string) => {
    if (
      status === 'Absent' ||
      status === 'Hold' ||
    ) {
      return true;
    }
    return false;
 }
 
 export default {hasChild}

Response JSON for the api is in the below format

 {
    ....,
    ....,
    child: {
        ...,
        ...,
        status: "Absent"
    }
 }

Could any one help me here.

  • Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Andy Ray Feb 21 '23 at 06:36
  • Let me check @AndyRay. Thanks for providing me with a link. – Ratna Srikanth Feb 21 '23 at 06:39
  • I tried this approach already. This approach leaves me infinite api calls loop @AndyRay – Ratna Srikanth Feb 21 '23 at 06:45

1 Answers1

1

Hi instead of relying upon state you can use it like this. Since state is async, you can use like this

const initialize = (parent: Parent) => {
  if (parent?.child) {
     const hasChild = UtilService.hasChild(parent?.child?.status);
      setIsCurrentSector(hasChild);
      alert(hasChild);
    }
}