Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading