Reputation: 1
I'm having trouble getting a prop to a child component. I'm calling the function like:
<ShowMedal debnr='55555' />
In the console I see the property is being passed.
Then in the ShowMedal component I want to pass the debnr to my API call, but it's not working.
import React, { useEffect, useState } from "react";
const ShowMedal = () => {
const [mpstotal, setMpsTotal] = useState([]);
const [ordertotal, setOrderTotal] = useState([]);
const getMpsTotal = async () => {
try {
const response = await fetch(`http://localhost:5000/mpstotal/${this.props.debnr}`);
const jsonData = await response.json();
setMpsTotal(jsonData);
} catch (err) {
console.error(err.message);
}
};
useEffect(() => {
getMpsTotal();
}, []);
What am I doing wrong here? :)
Upvotes: 0
Views: 48
Reputation: 11
Arrow functions do not have a this
binding of their own and there for it cannot reference props
from inside.
You can achieve the desired results in two ways:
const showMedal = ({ debnr }) => { // console.log(debnr) = 55555 }
props
as an argumentconst showMedal = props => {
//console.log(props.debnr) = 55555
}
Upvotes: 0
Reputation: 41893
Inside arrow functions this
keyword points to the window object, not the function body. Anyways, it's not a class, you can't access methods this way.
Just declare props
argument and use it.
const ShowMedal = ({ debnr }) => { // props destructuring
and then
const response = await fetch(`http://localhost:5000/mpstotal/${debnr}`);
Upvotes: 1