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

437
Visualizações
React-Axios => Cannot read properties of undefined (reading 'length')

I am trying to retrieve some data from an API. When I console the data it works fine:

import axios from 'axios';

export default function Model() {
  
    const url = "api.blabla.com/blabla"
    const [model, setModel] = useState()
    useEffect(() => {
      const axiosPosts = async () => {
        const response = await axios(url)
        setModel(response.data)
      };
      axiosPosts();
    }, []);

   console.log(model.slug) //prints the slug!!

    
    return (
      <div>
       {model.slug} : {model.name} // TypeError slug undefined
      </div>
    )  

What can be the problem with this code?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

It takes time for the api to respond, so at the start model is assigned the value of the parameter you passed to the useState() hook.

You passed nothing so during the first react render model is undefined.

One solution could be to change your template to:

{model?.slug} : {model?.name}

Or make it conditional

{model && (
  <>
    {model.slug} : {model.name}
  </>
)}
about 4 years ago · Juan Pablo Isaza Relatório

0

adding more to @ploppy's answer above, a common pattern here would be

import axios from 'axios';

export default function Model() {

const url = "api.blabla.com/blabla"
const [status, setStatus] = useState("idle");
const [model, setModel] = useState({
  slug: "",
  name: ""
})
useEffect(() => {
  setStatus("pending");
  const axiosPosts = async () => {
    try{
    const response = await axios(url)
    setModel(response.data)
    setStatus("resolved")
   }catch(error){
    console.log(error);
    setStatus("rejected");
   }
  };
  axiosPosts();
}, []);

console.log(model.slug) //prints the slug!!

if(status === "pending"){
    return (<div>Loading...</div>)
}
if(status === "rejected"){
    return (<div>Something went wrong!</div>)
}
return (
  <div>
   {model.slug} : {model.name} // TypeError slug undefined
  </div>
)  

This gives you a good advantage to handle API calls and their responses better.

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