Reputation: 1
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?
Upvotes: 0
Views: 61
Reputation: 1182
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[]
(i.e. 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
(i.e. 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::
.map
Upvotes: 1