I want to use the {prop.idno} from parent to child in componentDidMount() fetch call URL . How do I make use of idno in the URL to call different posts pages.
Is there a way to write it like this?
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts?userId= ${this.prop.idno} "
);
Parent Component :
return (
<>
<TogglePosts idno = {user.id}/>
</>
)
Child Component:
export class TogglePosts extends Component {
constructor(props){
super(props);
this.state = {
on: false,
data: [],
loaded: false,
};
}
toggle = () => {
this.setState({
on: !this.state.on,
});
};
async componentDidMount() {
console.log("comp did mount");
try {
const response = await fetch(
"https://jsonplaceholder.typicode.com/posts?userId=1"
);
const data = await response.json();
console.log(data);
this.setState({ data: data, loaded: true });
} catch (err) {
console.log(err);
}
}
CodePudding user response:
You can try editing your response similar to this.
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?userId= ${this.props.idno}`
);
Note that I've used `(tilde) instead of "(double quotes)
Also use props
instead of prop
CodePudding user response:
Can you try accessing it using props.idno in the TogglePosts Component?
In the fetch statement you can do something like fetch(https://jsonplaceholder.typicode.com/posts?userId=${props.idno}
);
CodePudding user response:
Try this:
const response = await fetch(
`https://jsonplaceholder.typicode.com/posts?userId= ${this.props.idno}`
);
Template literal(``) is the ability to include expressions and variables within a string.