I want to show my data value in a label, do I have to use .map every time?
DB Call:
const { carId } = useParams();
const { carType, setCarType } = useState([]);
const getCar (carId) => {
CarTypes.GetCar(carId)
.then(response) => {
setCarType(response.data.data);
}
}
return {
<h2 className="title"> { carType.CarMake } </h2>
}
Is there a different way to do this? I'm not getting an error, but do I need to do the .map to get the value? It's only returning one value.
do I need to do this every time, the response will only has 1 value in it?
{ carType.map(data => (
<h2 className="title"> { carType.CarMake } </h2>
)}
CodePudding user response:
If you are really sure about it's always going to have one element in the array, you can assign it using array definition like the following.
const { carId } = useParams();
const [carType, setCarType] = useState([]);
const getCar (carId) => {
CarTypes.GetCar(carId).then({data}) => {
// See array definition like in the useState
const [singleCar] = data.data;
setCarType(singleCar);
}
}
return {
<h2 className="title"> { carType.CarMake } </h2>
}
You can use it like that without using map()
CodePudding user response:
I think it's because, in the first rendering, your state "carType" is empty, so it cannot find the preperty "CarMake", so try this instead :
{!!carType.length &&
<h2 className="title"> { carType.CarMake } </h2>
}