简体   繁体   中英

Object component as Prop React Typescript

I Have a type Data:

export type Data = {

    id:Number;
    name:String;
    username:String;
    email:String;
    phone:String;
    website:String;

}

I wanna fetch data from a api. I'm using typescript so Data is a prop:

const App  = ()=>{
  const url = "https://jsonplaceholder.typicode.com/users/1";
 
  const [userData, setUserData] =  useState<Data[]>([]);

  const getUserData = async () => {
    let response = await fetch(url);
    let json = await response.json();
    setUserData(json);
  };

  useEffect(() => {
    getUserData();
  }, []);
  return (
    <div>
      <h2>User Data</h2>
   
          <div>
            {userData.map( (item,index)=>{
             return(
              <div key={index}>
               <strong>Name: </strong>
            {item.name}
         
            <strong>Website: </strong>
            {item.website}
         
         
            <strong>Email: </strong>
            {item.email}
         
         
            <strong>Phone: </strong>
            {item.phone}
            </div>
             )

            } )}
        </div>
    </div>
    )
}

I am getting an error in my code 'userData.map' is not a function and i don´t wanna use setUserData([json]) . Is there an alternative?

It is not clear from the endpoint but if you are getting a single Data element from it you can:

  • store the data doing setUserData([json]) , this is perfectly fine and correct. You could also create the array first then push the data but that is really just making the code longer.

  • Change how you store the data as you don't have an array of elements so you can do this instead:

const App  = ()=>{
  const url = "https://jsonplaceholder.typicode.com/users/1";
 
  const [userData, setUserData] =  useState<Data | undefined >(undefined);

  const getUserData = async () => {
    let response = await fetch(url);
    let json = await response.json();
    setUserData(json);
  };

  useEffect(() => {
    getUserData();
  }, []);
  return (
    <div>
      <h2>User Data</h2>
   
          <div>
            {userData ? (<div>
               <strong>Name: </strong>
            {userData.name}
         
            <strong>Website: </strong>
            {userData.website}
         
         
            <strong>Email: </strong>
            {userData.email}
         
         
            <strong>Phone: </strong>
            {userData.phone}
            </div>
             ) : null
            }
        </div>
    </div>
    )
}

Old answer to previous version of the question

If json has the shape Data[] (ie returns multiple objects) you just need to do setUserData(json) . no need to do a map to set the data on the state.

If instead json has the shape Data (ie returns a single object) then you need to set that object in an array before setting that to state. The more direct way is as you suggest at the end to use setUserData([json]) but you could also create the array first and push the data later to the array, something like this:

let json = data;
const dataArray = [];
dataArray.push(json);
setUserData(dataArray);

It would be better if you can be a bit more specific about::

  • The return type of the endpoint
  • What you want to achieve in general, to store the data in the state as it is?, store it as an array? something else? Why was relevant to use .map

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM