Created
August 29, 2020 14:19
-
-
Save thomaslombart/5222570fc84fb920d22706852f35420d to your computer and use it in GitHub Desktop.
An example of a Posts app written with React
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let nextId = 0 | |
export const addPost = (post) => { | |
return new Promise((resolve, reject) => { | |
setTimeout(() => { | |
if (Math.random() > 0.1) { | |
resolve({ status: 200, data: { ...post, id: nextId++ } }) | |
} else { | |
reject({ | |
status: 500, | |
data: "Something wrong happened. Please, retry.", | |
}) | |
} | |
}, 500) | |
}) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React from "react" | |
import { addPost } from "./api" | |
function Posts() { | |
const [posts, addLocalPost] = React.useReducer((s, a) => [...s, a], []) | |
const [formData, setFormData] = React.useReducer((s, a) => ({ ...s, ...a }), { | |
title: "", | |
content: "", | |
}) | |
const [isPosting, setIsPosting] = React.useState(false) | |
const [error, setError] = React.useState("") | |
const post = async (e) => { | |
e.preventDefault() | |
setError("") | |
if (!formData.title || !formData.content) { | |
return setError("Title and content are required.") | |
} | |
try { | |
setIsPosting(true) | |
const { | |
status, | |
data: { id, ...rest }, | |
} = await addPost(formData) | |
if (status === 200) { | |
addLocalPost({ id, ...rest }) | |
} | |
setIsPosting(false) | |
} catch (error) { | |
setError(error.data) | |
setIsPosting(false) | |
} | |
} | |
return ( | |
<div> | |
<form className="form" onSubmit={post}> | |
<h2>Say something</h2> | |
{error && <p className="error">{error}</p>} | |
<input | |
type="text" | |
placeholder="Your title" | |
onChange={(e) => setFormData({ title: e.target.value })} | |
/> | |
<textarea | |
type="text" | |
placeholder="Your post" | |
onChange={(e) => setFormData({ content: e.target.value })} | |
rows={5} | |
/> | |
<button className="btn" type="submit" disabled={isPosting}> | |
Post{isPosting ? "ing..." : ""} | |
</button> | |
</form> | |
<div> | |
{posts.map((post) => ( | |
<div className="post" key={post.id}> | |
<h2>{post.title}</h2> | |
<p>{post.content}</p> | |
</div> | |
))} | |
</div> | |
</div> | |
) | |
} | |
export default Posts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment