adrianhajdin / project_mern_memories

This is a code repository for the corresponding video tutorial. Using React, Node.js, Express & MongoDB you'll learn how to build a Full Stack MERN Application - from start to finish. The App is called "Memories" and it is a simple social media app that allows users to post interesting events that happened in their lives.
https://youtube.com/playlist?list=PL6QREj8te1P7VSwhrMf3D3Xt4V6_SRkhu
4.95k stars 1.83k forks source link

Part 1: Create a Post ... Redux createStore issue! #177

Open AAdewunmi opened 7 months ago

AAdewunmi commented 7 months ago

Hi, Form isnt sending post data (creator: '', title: '', message: '', tags: '', selectedFile: '') to mongodb. From console log, I can see the post request being fulfilled but the array is empty and mongodb hasn't received the post data. I've got my /3000 & /5000 servers running without error and mongodb cluster is running. Any suggestions for a fix? Thanks.

Screenshot 2023-12-06 at 16 25 06

Screenshot 2023-12-06 at 16 32 11

/api/index.js

import axios from 'axios';

const url = 'http://localhost:5000/posts';

export const fetchPosts = () => axios.get(url);
export const createPost = (newPost) => axios.post(url, newPost);

/actions/posts.js

import * as api from '../api';

export const getPosts = () => async (dispatch) => {
  try {
    const { data } = await api.fetchPosts();
    dispatch({ type: 'FETCH_ALL', payload: data });
  } catch (error) {
    console.log(error.message);
  }
};

export const createPost = (post) => async (dispatch) => {
  try {
    const { data } = await api.createPost(post);
    dispatch({type: 'CREATE', payload: data});
  } catch (error) {
    console.log(error.message)
  }
};

/Form/Form.js

import React, { useState } from "react";
import TextField from '@material-ui/core/TextField';
import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
import Paper from "@material-ui/core/Paper";
import FileBase from 'react-file-base64';
import { useDispatch } from 'react-redux';
import useStyles from "./styles.js";
import { createPost } from "../../actions/posts.js";

const Form = () => { 
    const [postData, setPostData] = useState({
      creator: '',
      title: '',
      message: '',
      tags: '',
      selectedFile: ''
    });
    const dispatch = useDispatch();
    const classes = useStyles();
    const handleSubmit = (e) => {
      e.preventDefault();
      dispatch(createPost(postData));
    };
    const clear = () => {};

    return (
      <Paper className={classes.paper}>
        <form
          autoComplete="off"
          noValidate
          className={`${classes.root} ${classes.form}`}
          onSubmit={handleSubmit}
        >
          <Typography variant="h6">Creating a Memory</Typography>
          <TextField
            name="creator"
            variant="outlined"
            label="Creator"
            fullWidth
            value={postData.creator}
            onChange={(e) =>
              setPostData({ ...postData, creator: e.target.value })
            }
          />
          <TextField
            name="title"
            variant="outlined"
            label="Title"
            fullWidth
            value={postData.title}
            onChange={(e) =>
              setPostData({ ...postData, title: e.target.value })
            }
          />
          <TextField
            name="message"
            variant="outlined"
            label="Message"
            fullWidth
            value={postData.message}
            onChange={(e) =>
              setPostData({ ...postData, message: e.target.value })
            }
          />
          <TextField
            name="tags"
            variant="outlined"
            label="Tags"
            fullWidth
            value={postData.tags}
            onChange={(e) => setPostData({ ...postData, tags: e.target.value })}
          />
          <div className={classes.fileInput}>
            <FileBase
              type="file"
              multiple={false}
              onDone={({ base64 }) =>
                setPostData({ ...postData, selectedFile: base64 })
              }
            />
          </div>
          <Button
            className={classes.buttonSubmit}
            variant="contained"
            color="primary"
            size="large"
            type="submit"
            fullWidth
          >
            Submit
          </Button>
          <Button
            variant="contained"
            color="secondary"
            size="small"
            onClick={clear}
            fullWidth
          >
            Clear
          </Button>
        </form>
      </Paper>
    );
}

export default Form;

/reducers/posts.js

export default (posts = [], action) => {
    switch (action.type) {
        case 'FETCH_ALL':
            return action.payload;
        case 'CREATE':
            return [...posts, action.payload];
        default:
            return posts;
    }
}
Sujal059 commented 6 months ago

Can I try to solve this bug?

AAdewunmi commented 6 months ago

Yes you can ...

AAdewunmi commented 6 months ago

Issue fixed! If you are having issues with Redux createStore() being depreciated, here's how to use configureStore():

  1. Run on server side console ->

    NPM

    npm install @reduxjs/toolkit

    Yarn

    yarn add @reduxjs/toolkit

  2. Include configureStore() in your client/src/index.js file

import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
// import { createStore, applyMiddleware, compose} from "redux";
// import thunk from "redux-thunk";
import { configureStore } from "@reduxjs/toolkit";
import reducers from "./reducers";
import App from "./App";
import "./index.css";

// const store = createStore(reducers, compose(applyMiddleware(thunk)));
const store = configureStore({ reducer: reducers });
ReactDOM.render(
    <Provider store={store}>
       <App />
    </Provider>,
  document.getElementById("root")
);

Job done!

Screenshot 2023-12-25 at 10 11 16

Screenshot 2023-12-25 at 10 11 43

A-bhiSheKumar commented 6 months ago

https://github.com/A-bhiSheKumar/collegiateVoice

I shared my link to that repo with you. Please check it out.