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

88
Visualizações
React API request is being made before props are sent

In my React project I'm trying to fetch some data from a database when a Link is pressed. When I do this, I can see that my props are undefined which causes a blank React page to be rendered.

I verified that id was not undefined as a prop by logging it when the Link is pressed. However, when I log it in the useEffect() hook it's undefined. How can I only make the request once the props have been passed?

const user = useContext(UserContext);

const id = props.followerId;

useEffect(() => {
        axios
            .get(`http://localhost:3000/users/followers/${id})
            .then((res) => {
                if (res.status === 200) {
                    user.setFollower(res.data);
                }
            })
            .catch((err) => {
                console.log(err);
            });
    }
}, []);
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can add id in dependency array so that if the id changes then the useEffect will run

and add a guard clause in useEffect so that request will only go if there is an id as:

const id = props.followerId;

useEffect(() => {
    if (id) {   // IF GUARD CLAUSE ONLY RUN IF ID IS SOMETHING
        axios
            .get(`http://localhost:3000/users/followers/${id}`)
            .then((res) => {
                if (res.status === 200) {
                    user.setFollower(res.data);
                }
            })
            .catch((err) => {
                console.log(err);
            });
    }
}, [id]);   // ADD ID IN DEPENDENCY ARRAY
about 4 years ago · Juan Pablo Isaza Relatório

0

You need to add id as dependency in useEffect. Moreover, add a boolean check on id too.

const user = useContext(UserContext);

const id = props.followerId;

useEffect(() => {
!!id & & axios
            .get(`http://localhost:3000/users/followers/${id})
            .then((res) => {
                if (res.status === 200) {
                    user.setFollower(res.data);
                }
            })
            .catch((err) => {
                console.log(err);
            });
    }
}, [id]);
about 4 years ago · Juan Pablo Isaza Relatório

0

useEffect with empty array means it only execute when component mount. if you use id in useEffetc dependency array then it will execute whenever id change its value and on mount also. so if id exist then call getFollower. like this

const user = useContext(UserContext);

const id = props.followerId;

useEffect(() => {
   const getFollower=(uid)=>{  
       axios.get(`http://localhost:3000/users/followers/${uid}`)
            .then((res) => {
                if (res.status === 200) {
                    user.setFollower(res.data);
                }
            })
            .catch((err) => {
                console.log(err);
            });
       }
   }

if(id) getFollower(id)
}, [id]);
about 4 years ago · Juan Pablo Isaza 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