Home > Net >  How to get an array's first object element into a state and pass it to a component?
How to get an array's first object element into a state and pass it to a component?

Time:01-17

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

CodePudding user response:

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.

  •  Tags:  
  • Related