Skip to content

Instantly share code, notes, and snippets.

@amcsi
Created June 3, 2024 10:41
Show Gist options
  • Save amcsi/da15614591653b5d9ef14322d1d4d713 to your computer and use it in GitHub Desktop.
Save amcsi/da15614591653b5d9ef14322d1d4d713 to your computer and use it in GitHub Desktop.
import { useSelector, useDispatch } from 'react-redux';
import { useState, useEffect } from 'react';
function EditPostComponent({id}) {
const dispatch = useDispatch();
// The initially loaded post
const post = useSelector(state => state.posts.postData);
useEffect(() => {
if (id) {
dispatch(loadPost(id));
return () => {
dispatch(resetPost());
}
}
}, [id]);
const [postDraft, setPostDraft] = useState(null);
/* Alternatively:
const form = useForm()
*/
// This useEffect is important! This updates the draft based on the last data
// loaded from the API.
useEffect(() => {
setPostDraft(post);
/* Alternatively, with useForm():
form.reset(postDraft);
*/
}, [post]);
async function saveForm() {
const result = await axios.post(...)
dispatch(successPost(result));
// Alternatively, rather than axios.post directly, call an a ction that
// does the POST for you, and ends up automatically making sure
// Redux's state.posts.postData gets set to the latest fetched data.
// Alternatively, if the POST response does not give you the same format
// of data than if you loaded the page, then refetch manually, like so:
// dispatch(loadPost(id));
}
return (
<form onSubmit={saveForm}>
<textarea onChange={event => {
setPostDraft(postDraft => ({...postDraft, text: event.target.value}));
}}>{postDraft.text}</textarea>
<button type="submit">Submit</button>
</form>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment