Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
AAdewunmi opened this issue Dec 6, 2023 · 4 comments
Open

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

AAdewunmi opened this issue Dec 6, 2023 · 4 comments

Comments

@AAdewunmi
Copy link

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;
    }
}
This was referenced Dec 7, 2023
@Sujal059
Copy link

Can I try to solve this bug?

@AAdewunmi
Copy link
Author

Yes you can ...

@AAdewunmi AAdewunmi changed the title Part 1: Create a Post ... Post Request not sending information to database! Part 1: Create a Post ... Redux createStore issue! Dec 17, 2023
@AAdewunmi
Copy link
Author

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

  1. 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

@AAdewunmi AAdewunmi reopened this Dec 25, 2023
@A-bhiSheKumar
Copy link

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

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants