Skip to content

Instantly share code, notes, and snippets.

@jim-clark
Last active May 8, 2024 20:33
Show Gist options
  • Save jim-clark/83a70ee47db7b21c0f170201c830e743 to your computer and use it in GitHub Desktop.
Save jim-clark/83a70ee47db7b21c0f170201c830e743 to your computer and use it in GitHub Desktop.

MERN-Stack CRUD Code Flow

Note: The code above is not meant to be complete.

FEATURE A - Load & Display Posts Upon First Render

STEP DESCRIPTION
A1 After the <PostListPage> has rendered for the first time, the useEffect function runs calling postsAPI.getAll() in the posts-api.js API module.
A2 The getAll() function delegates making the AJAX request by calling the sendRequest() function.
A3 & A4 The sendRequest() function uses the browser's fetch function to send the AJAX request to the server where the request flows through the Express app's middleware until it matches the route.
A5 The route calls the postsCtrl.getAll() controller action which uses the Post model to retrieve all posts for the logged in user.
A6 The controller action responds to the AJAX request using res.json(posts) sending back an array of the user's posts - completing the request initiated by postsAPI.getAll(). The connecting line is dashed because the posts actually flow back through the fetch(), sendRequest(), postsAPI.getAll() functions.

FEATURE B - Create Post When Form is Submitted in Child Component

STEP DESCRIPTION
B1 The user submits the form in <PostForm> which causes its handleSubmit event handler to execute.
B2 The event handler, after preventing the default action of the form being submitted to the server, calls the handleAddPost() function passed to it as a prop from <PostListPage> with an argument of the data for the new post (content).
B3 The handleAddPost() function calls postsAPI.add(postData) in the posts-api.js API module.
B4 The add() function in posts-api.js delegates making the AJAX request by calling the sendRequest() function.
B5 & B6 The sendRequest() function uses the browser's fetch function to send the AJAX request to the server where the request flows through the Express app's middleware until it matches the route.
B7 The route calls the postsCtrl.create() controller action which uses the Post model to create the user's new post.
B8 The controller action responds to the AJAX request using res.json(post) sending back the user's new post - completing the request initiated by postsAPI.add(). The connecting line is dashed because the post actually flows back through the fetch(), sendRequest(), postsAPI.add() functions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment