Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

271
Vistas
Best practice of setting state from axios request

I have an api.js file with the following function:

export const login =  (loginUserName, loginPassword, setUser) => {
    axios({
        method: 'post',
        data: {
            username: loginUserName,
            password: loginPassword
        },
        withCredentials: true,
        url: '...........'
    }).then(async (res) => {
        if (res.data.loggedIn === true) setUser(loginUserName);
    });
};

My useState hooks looks the following:

const [ user, setUser ] = useState({});

I was wondering, instead of sending the setUser function from my Login component like I do:

login(userName,password,setUser);

which is in another file, how can I do it from outside of the function like the following:

setUser(login(userName,password));

So in case the function did retrieve the information I wanted it'll return it (in this case the username), and in case not it will set the user as undefined or something.

I tried using

export const login =  (loginUserName, loginPassword) => {
   axios({
       method: 'post',
       data: {
           username: loginUserName,
           password: loginPassword
       },
       withCredentials: true,
       url: '............'
   }).then(async (res) => {
       if (res.data.loggedIn === true) return loginUserName;
   });
};

But I had some struggling with the async function. It seems like it wont return that information for some reason. if I had to guess it returns it only for the axios function or something.. How do I get the effect I am looking for and what's the best practice? Is sending the "setUser" function considered a good practice or is it better trying to get rid of it?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Your setUser function is only valid inside a component that declares it, so yes, simply return the fetch result and handle setting the state inside that particular component.

And the reason you don't get anything returned could be either the request didn't succeed (check your browser's network tab and the relevant response) or that you didn't await the result (fetching is always an asonchrynous operation, so you have to expect the response with a delay).

You could do sth like this:

useEffect(() => {
  (async () => {
    const username = await login(userName,password,setUser);
    setUser(username);
  })();
}, []);
over 4 years ago · Santiago Trujillo Denunciar

0

If I need a state object that I need to use along the flow of my app, like a user object that I'm planning to pass to most child components. Then I'd rather use Redux library to create a store that I can access in all components.

There would be a lot to do to get it work, so I'd be careful while reading the Documentation, but it's worth the work with the given tools.

You can then access/manipulate store states like the following:

import React, { useState } from 'react';
import { useAppSelector, useAppDispatch } from 'app/hooks';
import { decrement, increment } from './counterSlice';

function login(loginUserName, loginPassword) {
    const dispatch = useAppDispatch();

    axios({
        method: 'post',
        data: {
            username: loginUserName,
            password: loginPassword
        },
        withCredentials: true,
        url: '............'
    }).then(async (res) => {
        if (res.data.loggedIn === true) {
            dispatch(setUser(loginUserName));
        }
    };
}

export function Login() {
    login("User Name", "********");

    const user = useAppSelector((state) => state.user.value);
    console.log(user);
}
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda