- I have a parent app which contains a handler function (handleChallengeSave).
- The handler function triggers a useState (setSavedChallenge) in the parent.
- The handler function is passed down as props to the child.
I’m getting an ‘Unhandled Rejection (TypeError): X is not a function’ error. However if I change nothing other than moving the state to the child, it works.
Eg:
This doesn’t work:
Parent (App.js)
JavaScript
x
22
22
1
const App = () => {
2
const [savedChallenge, setSavedChallenge] = useState("");
3
4
const handleChallengeSave = (challenge) => {
5
setSavedChallenge(challenge);
6
};
7
8
return (
9
<>
10
<Router>
11
<Route
12
path="/"
13
exact
14
component={Home}
15
handleChallengeSave={handleChallengeSave}
16
/>
17
</Router>
18
</>
19
);
20
};
21
22
The Child (Home.js)
JavaScript
1
37
37
1
const Home = ({ handleChallengeSave }) => {
2
3
const getRequestUserChallengeDb = async () => {
4
await axios
5
.get(`${USER_CHALLENGE_DB_LINK}/${STRAVA_ID}`)
6
.then((res) => {
7
if (res.status === 200) {
8
console.log("Yes keen bean! You're in a challenge.");
9
let yourCurrentChallenge = res.data.currentChallenge;
10
handleChallengeSave(yourCurrentChallenge);
11
}
12
if (res.status === 201) {
13
console.log(
14
"You ain't in a challenge mate. Head to the challenges page to join one!"
15
);
16
}
17
})
18
.catch((error) => {
19
throw error;
20
});
21
};
22
23
getRequestUserChallengeDb();
24
25
return (
26
<>
27
<Navbar />
28
<div className="homepage_container">
29
<h2>Hi {window.localStorage.firstName}</h2>
30
</div>
31
<Challengebutton />
32
</>
33
);
34
};
35
36
export default Home;
37
Any help MUCH appreciated!
Advertisement
Answer
Issue
The Route
component doesn’t pass additional props on to children.
Solution
Render Home
on the render
prop to pass in additional props.
JavaScript
1
13
13
1
<Router>
2
<Route
3
path="/"
4
exact
5
render={(routeProps) => (
6
<Home
7
{routeProps}
8
handleChallengeSave={handleChallengeSave}
9
/>
10
)}
11
/>
12
</Router>
13
Or render Home
as a child component.
JavaScript
1
12
12
1
<Router>
2
<Route
3
path="/"
4
exact
5
>
6
<Home
7
{routeProps}
8
handleChallengeSave={handleChallengeSave}
9
/>
10
</Route>
11
</Router>
12