after a lot of searching i keep finding how to send Data from react to django api using classes not functions so how would i convert this for exmaple to a functional component (this is not my code, just an example)
export default class CreateRoomPage extends Component {
constructor(props) {
super(props);
this.state = {
guestCanPause: this.props.guestCanPause,
votesToSkip: this.props.votesToSkip,
errorMsg: "",
successMsg: "",
};
this.handleRoomButtonPressed = this.handleRoomButtonPressed.bind(this);
this.handleVotesChange = this.handleVotesChange.bind(this);
}
handleGuestCanPauseChange(e) {
this.setState({
guestCanPause: e.target.value === "true" ? true : false,
});
}
handleRoomButtonPressed() {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
votes_to_skip: this.state.votesToSkip,
guest_can_pause: this.state.guestCanPause,
}),
};
fetch("/api/create-room", requestOptions)
.then((response) => response.json())
.then((data) => this.props.history.push("/room/" + data.code));
}
renderCreateButtons() {
return (
<Grid container spacing={1}>
<Grid item xs={12} align="center">
<Button
color="primary"
variant="contained"
onClick={this.handleRoomButtonPressed}
>
Create A Room
</Button>
</Grid>
</Grid>
);
}
}
I suggest learning React classes and DRF before trying to learn React functional components and hooks, simply because there are a lot more resources for learning class-based React.
If you did, you'd know that there is nothing special about converting this particular code to a functional component. Just lose "this" and declare the methods as functions (arrow functions/classic functions - it doesn't matter)
PS: There is nothing to lose by learning class-based React - it's almost the same, and most of the differences will help understand how React works/how classes work on computers (arguably important for any programmer).
im learning as well, my approach:
import { useHistory } from "react-router";
export default function CreateRoomPage () {
const history = useHistory();
const [guestCanPause, setGuestCanPause] = useState(true)
const [votesToSkip, setVotesToSkip] = useState(1)
const handleGuestCanPauseChange = () => {
setGuestCanPause(current => !current)
}
const handleVotesChange = (e) => {
setVotesToSkip(e.target.value)
}
const handleRoomButtonPressed = async () => {
const requestOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
votes_to_skip: votesToSkip,
guest_can_pause: guestCanPause,
}),
};
await fetch("/api/create-room", requestOptions)
.then((response) => response.json())
.then((data) => history.push("/room/" + data.code));
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.