Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

111
Views
LLAMADAS API de React Native UseEffect

¿Cómo manejar múltiples llamadas api en el mismo render?

Ejemplo :

Quiero obtener información de la primera llamada API como esta, por ejemplo:

 const getUserInfo = async () => { const response = await axios .get(`${API}/api/tenants/${app.tenant}/users/me`, axiosConfig) .then((r) => { return r.data; }) .catch((e) => { console.log("ERORR", e); }); return response; }; const USER_INFO_SETTER = async () => { const fulldata = await getUserInfo(); setUsername(fulldata.username); setDisplayname(fulldata.display_name); setId(fulldata.id); getAvatarId(fulldata.profile_image); setFirstName(fulldata.first_name); setLastName(fulldata.last_name); }; useEffect(() => { USER_INFO_SETTER(); }, [isFocused]);

y quiero usarlo instantáneamente para la próxima LLAMADA API que viene bajo esta llamada

ejemplo :

 const GET_ACTIVE_PROFILE_PICTURE = async () => { try { const rez = await axios .get(`${API}/api/documents/document/${user.avatar_id}`, axiosConfig) .then((r) => { return r.config.url; }) .catch((e) => { console.log("ERROR", e); }); return rez; } catch { console.log("error"); } }; const avatarSetted = async () => { const avatarLink = await GET_ACTIVE_PROFILE_PICTURE(); setProfileImage(avatarLink); }; useEffect(() => { avatarSetted(); console.log("123"); }, []);

Entonces, la pregunta es cómo usar la información que obtengo dentro de la primera llamada API justo después de eso en la llamada API a continuación. porque sin esa información, por ejemplo, user.id_picture, mi segunda llamada a la API devolverá 500.

Gracias por la ayuda :)

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

En primer lugar, crearía un par de funciones como esta:

 const getUserInfo = () => { // This contains the axios request and returns the response. }; const getActiveProfilePicture = () => { // This contains the axios request and returns the response. }; const fetchUserInfo = () => { // This calls the getter and uses the response to update state. }; const fetchActiveProfilePicture = () => { // This calls the getter and uses the response to update state. };

También presentaría 2 variables de estado, es posible que ya las tenga, por lo que este paso puede ser innecesario.

 const [avatarId, setAvatarId] = useState(null); const [profileImage, setProfileImage] = useState(null);

Complete la lógica para sus funciones que agregó anteriormente.

 const fetchUserInfo = useCallback(async () => { const response = await getUserInfo(); // Perform all state updates. setAvatarId(response.profile_image); }, []); const fetchActiveProfilePicture = useCallback(async () => { const response = await getActiveProfilePicture(); // Perform all state updates. setProfileImage(response); }, []);

Luego, crea dos useEffects :

  • Cuando el componente se monte, llame a fetchUserInfo .
  • Cuando se haya recuperado el avatarId y finalmente se haya establecido en el estado, llame a fetchActiveProfilePicture .
 useEffect(() => { fetchUserInfo(); }, [fetchUserInfo]); useEffect(() => { if(avatarId) { fetchActiveProfilePicture(); } }, [fetchActiveProfilePicture, name]);

Encontrará algunas advertencias de eslint ( react-hooks/exhaustive-deps ) dentro de este ejemplo acerca de envolver funciones en useCallback o colocar la lógica directamente en useEffect . Solo un aviso.

Aquí hay un ejemplo en CodeSandbox con PokeAPI.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!