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

184
Vistas
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 Respuestas
Responde la pregunta

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 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