'I can't get the props.match.params.id. It's said props is undefined
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>
);
}
Solution 1:[1]
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) {
Solution 2:[2]
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])
...
}
Solution 3:[3]
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
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Vivek Doshi |
| Solution 2 | |
| Solution 3 | Suraj Auwal |
