Home > Mobile >  How to call a variable inside a then method?
How to call a variable inside a then method?

Time:07-05

I'm getting client data from the backend and I'am using Axios to call that method. In then() when I get the response data, I want to make a condition that if its completed, to push it to the new array

export default function Client({selectedClient, setSelectedClient})

  console.log(selectedClient) //the value comes
  useEffect(() => {
    axios
      .get('api')
      .then((response) => {
        const { data } = response; //array of data
        console.log(selectedClient) // the value doesn't come
        data.forEach(element => {
          if (element.CLIENT_ID == selectedClient){
            console.log('single element', element)
          }
        });
      })
      .catch((error) => console.log("Get Method Error", error.message));
  }, []);

So when I put selectedClient inside the then(), it will be empty.

How can I solve this?

CodePudding user response:

You need to have selectedClient as a dependency in useEffect hook. So that hook can updated prop value when component mounts.

export default function Client({selectedClient, setSelectedClient})

  console.log(selectedClient) //the value comes
  useEffect(() => {
    if (selectedClient) {
     axios
      .get('api')
      .then((response) => {
        const { data } = response; //array of data
        console.log(selectedClient) // the value will come now.
        data.forEach(element => {
          if (element.CLIENT_ID == selectedClient){
            console.log('single element', element)
          }
        }});
      })
      .catch((error) => console.log("Get Method Error", error.message));
  }, [selectedClient]);

Note - You can remove the added if (selectedClient) { if you wanted to invoke the call even when it's not populated.

  • Related