Reputation: 45
I've tried to get the id from the URL (with props.match.params.id) and pass it into a variable to reuse it. But props is undefined. I don't know why.
Anyone can see if I've done something wrong?
import React, { useState, useEffect } from "react";
import axios from "axios";
export default function Recipes() {
const [recipes, setRecipes] = useState([]);
useEffect(() => {
const id = props.match.params.id;
const getRecipes = async () => {
const url = `http://localhost:8000/user/recipes/${id}`;
const result = await axios.get(url);
setRecipes(result.data);
console.log("test", recipes);
};
getRecipes();
}, []);
return (
<div>
{recipes.map(recipe => (
<p>{recipe.title}</p>
))}
</div>
);
}
Upvotes: 2
Views: 9533
Reputation: 10658
You need to make use of the useParams
hook from react-router-dom
for this instead.
Try this:
...
import { useParams } from 'react-router-dom'
export default function Recipes() {
...
const { id } = useParams()
useEffect(() => {
...
}, [id])
...
}
Upvotes: 9
Reputation: 318
Ah! I think you forget it add props as a param to you component. This is something I do very often.
Your component should be like this
export default function Recipes(props) {
//Your content
}
Upvotes: 0
Reputation: 58613
I think you forgot to add props in your functional component :
You can solve the error "It's said props is undefined"
By Change this :
export default function Recipes() {
TO
export default function Recipes(props) {
Upvotes: 3