Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

270
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda