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

191
Visualizações
How to get an array's first object element into a state and pass it to a component?

How it is possible to get the first object from the response data, and store that in a state?

I've tried something like this, where i use the setData and store the data's first object to it:

export default function BuildingsDetail({buildingId}) {
  const [data, setData] = useState({});
  const navigate = useNavigate();

  useEffect(()=> {
    if (!localStorage.getItem('token')) {
      navigate('/login');
    } else {
      fetch(Config.domain + 'kingdom/buildings/:'+buildingId, {
        headers: {'Authorization': 'Bearer '+localStorage.getItem('token')}
      })
      .then(res=>res.json())
      .then(data => {
        setData(data[0]);
      })
    }
  }, [buildingId])
  console.log(data);
  return(
    <div className='container'>
      <div className='building-details'>
        <img />
        <p></p>
        <p></p>
        {data.type === 'Academy' ? <BuildingsButton type={data.type} level={data.level}/> : ''}
        <BuildingsButton type={data.type} level={data.level}/>
      </div>
    </div>
  );

I'm getting undefined errors for data.type, which i can't understand since it should be an object which has a 'type' key to it.

Also when im logging out data, it says undefined.

The response from postman is the following:

[
    {
        "id": 63,
        "kingdom_id": 31,
        "type": "Academy",
        "level": 1,
        "hp": 100,
        "started_at": 1642410594584,
        "finished_at": 1642410654584
    }
]
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think that the problem is that you are trying to display data before it's loaded by the fetch call.

Change your state default value to null:

const [data, setData] = useState(null);

And add a condition to check if the data state is present before rendering the page:

if (!data) {
    return <>Loading data...</>
}

return (
  <div className='container'>
    <div className='building-details'>
      <img />
      <p></p>
      <p></p>
      {data.type === 'Academy' ? (
        <BuildingsButton type={data.type} level={data.level} />
      ) : (
        ''
      )}
      <BuildingsButton type={data.type} level={data.level} />
    </div>
  </div>
);

It should prevent the error.

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