Skip to content

Instantly share code, notes, and snippets.

@Herve07h22
Last active April 12, 2021 15:43
Show Gist options
  • Save Herve07h22/8b21a4e6bc0b7765e6ff6d5a5c58f8da to your computer and use it in GitHub Desktop.
Save Herve07h22/8b21a4e6bc0b7765e6ff6d5a5c58f8da to your computer and use it in GitHub Desktop.
React MVVM with hooks
import {useFriend} from '../model/useFriend'
export function FriendLine ({friend}) {
const {fullname, deleteFriend} = useFriend(friend)
return (<tr>
<td>{fullname}</td>
<td><button onclick={deleteFriend} /></td>
</tr>);
}
import {usePersonal} from '../model/usePersonal'
import {FriendLine} from '../../Friends/presentation/FriendLine'
export function Personal ({ id }) {
const {fullname, age, friends, setAge} = usePersonal(id)
return (<div>
<h1>{ fullname}</h1>
<input value={age} onChange={setAge} />
<table>
{
friends.map(FriendLine)
}
</table>
</div>);
}
import { useState } from "react";
export const useFriend = ({personalId, friend}) => {
const {
personalService,
} = useServices(); // React.Context to inject the services
const [fullname, ] = useState(friend.name)
const deleteFriend = personalService.removePresonalFriend(personalId, friend.id)
return {fullname, deleteFriend}
}
import { useEffect, useState } from "react";
export const usePersonal = ({id}) => {
const {
personalService,
} = useServices(); // React.Context to inject the services
const [fullname, setFullname] = useState()
const [age, setAge] = useState()
const [friends, setFriends] = useState([])
useEffect( () => {
personalService.find(id).then(personal => {
setFullname(personal.fullname)
setAge(personal.age)
setFriends(personal.friends)
})
}, [id, personalService] )
return {fullname, age, friends, setAge}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment