Skip to content

Commit

Permalink
Change to functional component
Browse files Browse the repository at this point in the history
  • Loading branch information
sevfurneaux committed Nov 13, 2024
1 parent 1a114f3 commit e04e9a8
Showing 1 changed file with 39 additions and 53 deletions.
92 changes: 39 additions & 53 deletions meinberlin/react/livequestions/QuestionUser.jsx
Original file line number Diff line number Diff line change
@@ -1,65 +1,51 @@
import React from 'react'
import React, { useEffect, useState, useCallback } from 'react'
import LikeCard from './LikeCard'

export default class QuestionUser extends React.Component {
constructor (props) {
super(props)
const QuestionUser = ({ is_on_shortlist: isOnShortlist, likes, handleLike, id, children, category, hasLikingPermission }) => {
const [, setIsOnShortlist] = useState(isOnShortlist)
const [likeCount, setLikeCount] = useState(likes.count)
const [sessionLike, setSessionLike] = useState(likes.session_like)

this.state = {
is_on_shortlist: this.props.is_on_shortlist,
is_live: this.props.is_live,
likes: this.props.likes.count,
session_like: this.props.likes.session_like
}
}
useEffect(() => {
setIsOnShortlist(isOnShortlist)
}, [isOnShortlist])

componentDidUpdate (prevProps) {
if (this.props.is_on_shortlist !== prevProps.is_on_shortlist) {
this.setState({
is_on_shortlist: this.props.is_on_shortlist
})
}
if (this.props.likes !== prevProps.likes) {
this.setState({
likes: this.props.likes.count,
session_like: this.props.likes.session_like
})
}
}
useEffect(() => {
setLikeCount(likes.count)
setSessionLike(likes.session_like)
}, [likes])

handleErrors (response) {
const handleErrors = (response) => {
if (!response.ok) {
throw Error(response.statusText)
throw new Error(response.statusText)
}
return response
}

handleLike () {
const value = !this.state.session_like
this.props.handleLike(this.props.id, value)
.then(this.handleErrors)
.then((response) => this.setState(
{
session_like: value,
likes: value ? this.state.likes + 1 : this.state.likes - 1
}
))
.catch((response) => { console.log(response.message) })
}
const handleLikeClick = useCallback(() => {
const newSessionLike = !sessionLike
handleLike(id, newSessionLike)
.then(handleErrors)
.then(() => {
setSessionLike(newSessionLike)
setLikeCount((prevLikes) => prevLikes + (newSessionLike ? 1 : -1))
})
.catch((error) => {
console.log(error.message)
})
}, [sessionLike, handleLike, id])

render () {
return (
<LikeCard
title={this.props.children}
category={this.props.category}
likes={{
count: this.state.likes,
session_like: this.state.session_like
}}
{...this.props.hasLikingPermission && {
onLikeClick: this.handleLike.bind(this)
}}
/>
)
}
return (
<LikeCard
title={children}
category={category}
likes={{
count: likeCount,
session_like: sessionLike
}}
{...(hasLikingPermission && { onLikeClick: handleLikeClick })}
/>
)
}

export default QuestionUser

0 comments on commit e04e9a8

Please sign in to comment.