reactjsnode.jsreact-nativeaxios

React Native - API request is returning data in a second call when calling it for the first time


Does anyone can help me with this. I a trying to make an app to give people access to political data and make better choices with it. By somehow data is being returned only in the second call usualy in the first atempty. But not always.

I hard coded the apiUrl so you dont need to complete by yourself and discard any hook problems.

this is my api helper/service:

import axios from "axios";

export const searchDeputy = async (stateValue, politicalPartyValue) => {
  if (stateValue === "TODOS" || stateValue === "Estado") {
    stateValue = "";
  }

  if (politicalPartyValue === "TODOS" || politicalPartyValue === "Partido") {
    politicalPartyValue = "";
  }

  const apiUrl = `https://dadosabertos.camara.leg.br/api/v2/deputados? 
  siglaUf=AM&siglaPartido=&ordem=ASC&ordenarPor=nome`;

  console.log(apiUrl);

  try {
    let response = await axios.get(apiUrl, {
      headers: {
        Accept: "application/json",
      },
    });

const searchDeputyData = await response.data.dados;

return searchDeputyData;
  } catch (error) {
    console.error("Error fetching data:", error);
    return null;
  }
};

and I am calling the function with this code:

<View className="p-2">
      <Pressable
        onPress={async () => {
          const response = await searchDeputy(
            stateValue,
            politicalPartyValue
          );

          await setSearchDeputyData(response);
          console.log(searchDeputyData);
        }}
      >
        <FontAwesome name="search" size={34} color="black" />
      </Pressable>
    </View>

I already tryied to delay the api call and call it without async, tryed fetch instead of axios but I got the same results.

Does anyone ever got this kind of issues.

I would prefer to meke only one call but i will try to make a second call if the first one returns no data.


Solution

  • If you are using JavaScript, you should know that useState is asynchronous. When you set a variable, it won't be updated immediately.

    That's why your :

    console.log(searchDeputyData);
    

    will not show the value you're expecting. Even if you add an await

    To address this, you can create a useEffect function that will be triggered when the state of your variable changes:

    
    useEffect(() => {
        console.log(searchDeputyData)
    }, [searchDeputyData]);