React component import data from db - javascript

I'm building a web app with React where I have a component (product.js), with a form connected to a db, and another component where I need to use the data inserted previously in the form. The form is working and is sending the info to the mongodb, but I'm struggling with getting the data to the last component (Output.js) where I need to access that data. The flow is from product.js to another comp, profile.js, and then to output.js. I'm surely missing or doing something wrong but so far haven't been able to make it work. Any help or suggestions on how to do it are greatly appreciated.
Product.js route:
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const Product = require('../models/product-model');
// POST route => to create a new product
router.post('/product', (req, res, next) => {
const { name, price, category } = req.body;
Product.create({
name,
price,
category
})
.then(response => {
res.json(response);
})
.catch(err => {
res.json(err);
});
});
// GET route => to retrieve a specific product
router.get('/product/:productId', (req, res, next) => {
Product.findById(req.params.productId)
.then(product => {
console.log("this is it>>>>>>>>>>>>>", product)
res.json(product);
})
.catch(error => {
res.json(error);
});
});
module.exports = router;
Product.js React component:
import React, {Component} from 'react';
import axios from 'axios';
class Products extends Component {
constructor(props){
super(props);
this.state = { name: "", price: "", category: "" };
}
handleFormSubmit = (event) => {
event.preventDefault();
this.props.history.push('/profile');
const name = this.state.name;
const price = this.state.price;
const category = this.state.category;
axios.post("http://localhost:5000/product", { name, price, category })
.then( () => {
this.props.getData();
console.log("added to db!");
this.setState({name: "", price: "", category: ""});
})
.catch( error => console.log(error) )
}
handleChange = (event) => {
const {name, value} = event.target;
this.setState({[name]: value});
}
render(){
return(
<div>
<form onSubmit={this.handleFormSubmit}>
<label>Name</label>
<input type="text" name="name" value={this.state.name} onChange={ e => this.handleChange(e)}/>
<label>Category</label>
<input type="text" name="category" value={this.state.category} onChange={ e => this.handleChange(e)}/>
<label>Price</label>
<input type="number" name="price" value={this.state.price} onChange={ e => this.handleChange(e)} />
<input type="submit" value="Submit" />
</form>
</div>
)
}
}
export default Products;
Output.js component:
import React, {Component} from 'react';
import axios from 'axios';
class Output extends Component {
constructor(props){
super(props);
this.state = {};
}
componentDidMount() {
this.getProduct();
}
getProduct = () => {
const params = this.props.match
console.log(this.props);
axios.get(`http://localhost:5000/product/:productId`)
.then( responseFromApi => {
console.log("this is it", responseFromApi);
const theProduct = responseFromApi.data;
console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>this is the product", theProduct);
this.setState(theProduct);
})
.catch(err => console.log(err));
}
render() {
return (
<div>
<h1>{this.state.price}</h1>
<h1>results</h1>
</div>
)
}
}
export default Output;

Related

Edit function not working for my CRUD App

I am building a simple CRUD app, and I have 90% of it working but for some reason I can't get the "edit" functionality to work. When I go to edit my team members name, nothing happens when I click "Edit Name". Worth noting, I copied the code from my "add user" component and modified were needed. Here is my code:
// EDIT USER
import React, { useState, useContext, useEffect } from 'react'
import { GlobalContext } from '../context/GlobalState'
import { Link, useNavigate, useParams } from 'react-router-dom'
import { Form, FormGroup, Label, Input, Button } from 'reactstrap'
const EditUser = (props) => {
const [selectedUser, setSelectedUser] = useState({
id: '',
name: ''
});
const { users, editUser } = useContext(GlobalContext);
const navigate = useNavigate();
const currentUserId = useParams(props);
useEffect(() => {
const userId = currentUserId;
const selectedUser = users.find((user) => user.id === userId);
if (selectedUser) {
setSelectedUser(selectedUser);
}
}, [currentUserId, users]);
const onSubmit = (e) => {
e.preventDefault()
editUser(selectedUser)
navigate('/');
}
const onChange = (e) => {
setSelectedUser({...selectedUser, [e.target.name]: e.target.value})
}
return (
<div className='container w-25'>
<Form className='form-control' onSubmit={onSubmit}>
<FormGroup>
<Label>Edit Name</Label>
<Input type='text' name='name' value={selectedUser.name} onChange={onChange} placeholder='Enter Name'></Input>
</FormGroup>
<Button type='submit'>Edit Name</Button>
<Link to='/' className='btn btn-danger m-2'>Back</Link>
</Form>
</div>
)
}
export default EditUser
// ADD USER
import React, { useState, useContext } from 'react'
import { GlobalContext } from '../context/GlobalState'
import { Link, useNavigate } from 'react-router-dom'
import { v4 as uuid } from 'uuid';
import { Form, FormGroup, Label, Input, Button } from 'reactstrap'
const AddUser = () => {
const [name, setName] = useState('');
const { addUser } = useContext(GlobalContext);
const navigate = useNavigate();
const onSubmit = (e) => {
e.preventDefault()
const newUser = {
id: uuid(),
name: name
}
addUser(newUser);
navigate('/');
}
const onChange = (e) => {
setName(e.target.value);
}
return (
<div className='container w-25'>
<Form className='form-control' onSubmit={onSubmit}>
<FormGroup>
<Label>Name</Label>
<Input
type='text'
name={name}
value={name}
onChange={onChange}
placeholder='Enter Name'></Input>
</FormGroup>
<Button type='submit'>Submit</Button>
<Link to='/' className='btn btn-danger m-2'>Back</Link>
</Form>
</div>
)
}
export default AddUser
// GLOBAL CONTEXT
import React, { createContext, useReducer } from 'react';
import AppReducer from './AppReducer';
const initialState = {
users: []
};
// Create Context \\
export const GlobalContext = createContext(initialState);
// Provider Component \\
export const GlobalProvider = ({children}) => {
const [state, dispatch] = useReducer(AppReducer, initialState);
// Actions
const removeUser = (id) => {
dispatch({
type: 'REMOVE_USER',
payload: id
});
}
const addUser = (user) => {
dispatch({
type: 'ADD_USER',
payload: user
});
}
const editUser = (user) => {
dispatch({
type: "EDIT_USER",
payload: user
});
}
return(
<GlobalContext.Provider value={{
users: state.users,
removeUser,
addUser,
editUser
}}>
{children}
</GlobalContext.Provider>
)
}
// APP REDUCER
export default (state, action) => {
switch(action.type) {
case 'REMOVE_USER':
return {
users: state.users.filter(user => {
return user.id !== action.payload
})
}
case 'ADD_USER':
return {
users: [action.payload, ...state.users]
}
case 'EDIT_USER':
const updateUser = action.payload
const updateUsers = state.users.map(user => {
if(user.id === updateUser.id) {
return updateUser;
}
return user;
})
return {
users: updateUsers
}
default:
return state
}
}
Issue
The issue seems to be that the Edit component isn't accessing the route paths params object correctly, to reference the route path's userId param.
const currentUserId = useParams();
useEffect(() => {
const userId = currentUserId;
const selectedUser = users.find((user) => user.id === userId);
if (selectedUser) {
setSelectedUser(selectedUser);
}
}, [currentUserId, users]);
Here the entire params object is named currentUserId. In the useEffect hook callback this params object is assigned to a local variable userId and then used to find a matching user object in the users array. It's comparing a specific user's id property (a string type) to the entire params object (an object type). This OFC will never be equal and selectedUser is undefined and the local selectedUser state is never initialized to the user you are trying to edit.
Solution
Either access into the params object to correctly access the specific parameter:
const currentUserId = useParams();
useEffect(() => {
const userId = currentUserId;
const selectedUser = users.find((user) => user.id === userId.userId);
if (selectedUser) {
setSelectedUser(selectedUser);
}
}, [currentUserId, users]);
Or just destructure the userId path param directly:
const { userId } = useParams();
useEffect(() => {
const selectedUser = users.find((user) => user.id === userId);
if (selectedUser) {
setSelectedUser(selectedUser);
}
}, [userId, users]);
Suggestion
Initialize the selectedUser state directly. Use a useEffect hook to check if there is a user to edit and issue a back navigation if there is not one to edit.
const EditUser = () => {
const navigate = useNavigate();
const { userId } = useParams();
const { users, editUser } = useGlobalContext(); // *
const [selectedUser, setSelectedUser] = useState(
users.find((user) => user.id === userId)
);
useEffect(() => {
if (!selectedUser) navigate(-1);
}, [navigate, selectedUser]);
const onSubmit = (e) => {
e.preventDefault();
editUser(selectedUser);
navigate("/");
};
const onChange = (e) => {
setSelectedUser({ ...selectedUser, [e.target.name]: e.target.value });
};
return (
<div className="container w-25">
{selectedUser && (
<Form className="form-control" onSubmit={onSubmit}>
<FormGroup>
<Label>Edit Name</Label>
<Input
type="text"
name="name"
value={selectedUser.name}
onChange={onChange}
placeholder="Enter Name"
/>
</FormGroup>
<Button type="submit">Edit Name</Button>
<Link to="/" className="btn btn-danger m-2">
Back
</Link>
</Form>
)}
</div>
);
};
* Note: This was just a custom hook created for convenience in the context code:
const useGlobalContext = () => useContext(GlobalContext);

Trying to submit a user score with a button in react. Getting error message of saveScore is not a function

I am building a react application and part of the application is a quiz section. At the end of the quiz there is a button which can save the user score in the quiz to the database.
This is my express route
// #route Put api/profile/saveScore/:id
// #desc Save users quiz score to profile
// #access Private
router.put('/saveScore/:topic_id', checkObjectId('topic_id'), auth, async (req, {params: {topic_id } }, res) => {
const score = req.body.score
const topic = topic_id
const newUserTopic = {
score,
topic,
}
try {
const profile = await Profile.findOne({ user: req.user.id });
profile.topics.unshift(newUserTopic);
await profile.save();
res.json(profile)
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
})
The express route works no bother in postman so thinking the issue must be more on the react side.
This is my action route
// Save Quiz Score to users profile
export const saveScore = (topicId, payload) => async (dispatch) => {
try {
const res = await api.put(`/profile/saveScore/${topicId}`, payload);
dispatch({
type: GET_PROFILE,
payload: res.data
});
dispatch(setAlert('Topic Saved', 'success'));
} catch (err) {
const errors = err.response.data.errors;
if(errors) {
errors.forEach(error => dispatch(setAlert(error.msg, 'danger')))
}
dispatch({
type: PROFILE_ERROR,
payload: { msg: err.response.statusText, status: err.response.status }
});
}
};
This is my component
import React, { useEffect, useState, Fragment } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Spinner from '../layout/Spinner';
import QuizItem from './QuizItem';
import { getTopicById } from '../../actions/topic';
import { saveScore} from '../../actions/profile';
import { SaveScoreForm } from './SaveScoreForm';
const Quiz = ({ getTopicById, saveScore, topic: { topic, loading }, match }) => {
useEffect(() => {
getTopicById(match.params.id);
}, [getTopicById, match.params.id])
const [currentIndex, setCurrentIndex] = useState(0);
const [score, setScore] = useState(0);
const [showAnswers, setShowAnswers] = useState(false)
const [formData, setFormData] = useState({ score })
const handleAnswer = (answer) => {
if(!showAnswers) {
if(answer === topic[currentIndex].correct_answer) {
setScore(score + 1);
}
}
setShowAnswers(true);
};
const handleNextQuestion = () => {
setShowAnswers(false);
setCurrentIndex(currentIndex + 1);
}
console.log(currentIndex)
const onChange = (e) => {
setFormData({ ...formData, [e.target.name]: e.target.value })
}
const onSubmit = (e) => {
e.preventDefault();
const payload = new FormData();
payload.append('score', formData.score)
saveScore(payload, match.params.id);
}
return topic.length > 0 ? (
<div className='container'>
{currentIndex >= topic.length ? (
<Fragment>
<SaveScoreForm topic={topic} score={score} />
<form
onSubmit={e => onSubmit(e)}
>
<input
type='hidden'
value={score}
onChange={(e) => onChange(e)}
/>
<input type='submit' className='btn btn-primary1 my-1' />
</form>
</Fragment>
) : (
<QuizItem
key={topic.question}
topic={topic[currentIndex]}
showAnswers={showAnswers}
handleNextQuestion={handleNextQuestion}
handleAnswer={handleAnswer}
/>
)}
</div>
) : (
<Spinner/>
)
}
Quiz.prototype = {
getTopicById: PropTypes.func.isRequired,
topic: PropTypes.object.isRequired
}
const mapStateToProps = state => ({
topic: state.topic,
showAnswers: state.showAnswers,
handleNextQuestion: state.handleNextQuestion,
handleAnswer: state.handleAnswer
})
export default connect(mapStateToProps, { getTopicById })(Quiz)
Child component
import React from 'react'
export const SaveScoreForm = ({ score, topic, }) => {
return (
<div>
<div className='bg-primary1 p-2 my-4'>
<h1 className='large'>Review Your Score</h1>
<p className="lead">Quiz ended! Your score is: {(score/topic.length) * 100}%</p>
<p>Save your score to your profile or take the quiz again!</p>
</div>
</div>
);
};
export default SaveScoreForm;
TypeError: saveScore is not a function
Any help or pointers in the right direction would be very much appreciated.
Thanks
You are importing import { saveScore} from '../../actions/profile';
But then you have this prop
const Quiz = ({ getTopicById, saveScore
// ----------------------------^
which is overriding saveScore in your components context. Unless you are passing a saveScore prop while initialising <Quiz> it'll be undefined.
If you want to import the saveScore module just remove this prop variable.

When I first click the delete button, all the notes are disappeared but, when I refresh the page it works just fine

I tried almost everything. I tested my API to ensure that the problem is not with it. It happens just one time when you visit the page. However, when you refresh it works fine.
Before Clicking delete:
Click here to see the image
After clicking delete button: Click here to see the image
Backend Route (home.route.js):
const express = require("express");
const mongoose = require("mongoose");
const Note = require("../models/note.model.js");
const router = express.Router();
router.get("/", (req, res) => {
Note.find()
.then(notes => res.json(notes))
.catch(err => res.status(400).json("Error: " + err));
});
router.post("/", (req, res) => {
const note = req.body;
const newNote = new Note(note);
newNote.save()
.then(() => res.json("Note added"))
.catch(err => res.status(400).json("Error: " + err));
});
router.delete("/", (req, res) => {
const idWeGotFromReact = req.body.noteId;
Note.findByIdAndDelete(idWeGotFromReact)
.then(() => res.json('Note deleted.'))
.catch(err => res.status(400).json('Error: ' + err));
})
module.exports = router;
React Code:
Code for the Note Component:
import React from "react";
import axios from 'axios';
import DeleteIcon from '#material-ui/icons/Delete';
function Note(props) {
function handleClick() {
const id = props.noteId;
axios({
method: 'delete',
url: 'http://localhost:5000',
data: {
noteId: id
}
});
props.onDelete(id);
}
return (
<div className="note">
<h1>{props.title}</h1>
<p>{props.content}</p>
<button name={props.noteId} onClick={handleClick}>
<DeleteIcon />
</button>
</div>
);
}
export default Note;
Code for the Main App component:
import React, { useState, useEffect } from "react";
import axios from "axios";
import Header from "./Header";
import Footer from "./Footer";
import Note from "./Note";
import CreateArea from "./CreateArea";
function App() {
const [notes, setNotes] = useState([]);
useEffect(() => {
axios
.get('http://localhost:5000')
.then(res => {
setNotes(res.data);
});
}, []);
function addNote(newNote) {
setNotes(prevNotes => {
return [...prevNotes, newNote];
});
}
function deleteNote(id) {
setNotes(notes => {
return notes.filter((noteItem) => {
return noteItem._id !== id;
});
});
}
function NoteList() {
return (
notes.map((noteItem) => {
return (
<Note
key={noteItem._id}
id={noteItem._id}
title={noteItem.title}
content={noteItem.content}
onDelete={deleteNote}
noteId={noteItem._id}
/>
);
})
);
}
return (
<div>
<Header />
<CreateArea onAdd={addNote} />
<NoteList />
<Footer />
</div>
);
}
export default App;
Input Component:
import React, { useState } from "react";
import axios from "axios";
function CreateArea(props) {
const [note, setNote] = useState({
title: "",
content: ""
});
function handleChange(event) {
const { name, value } = event.target;
setNote(prevNote => {
return {
...prevNote,
[name]: value
};
});
}
function submitNote(event) {
props.onAdd(note);
setNote({
title: "",
content: ""
});
event.preventDefault();
axios
.post('http://localhost:5000', note)
.then(res => {
console.log(res);
console.log(res.data);
});
}
return (
<div>
<form action="/" method="post">
<input
name="title"
onChange={handleChange}
value={note.title}
placeholder="Title"
/>
<textarea
name="content"
onChange={handleChange}
value={note.content}
placeholder="Take a note..."
rows="3"
/>
<button className="button" onClick={submitNote}>Add</button>
</form>
</div>
);
}
export default CreateArea;
I would also appreciate if you can provide a review of my code because I am a beginner and that would definitely help me.
Try this approach, (just an assumption)
function deleteNote(id) {
setNotes(notes => {
const filteredNotes = notes.filter((noteItem) => {
return noteItem._id !== id;
});
return [...filteredNotes];
});
}

Refactoring React class to hooks - Entity update component

I have this React component that I use to update business entities. It basically fetches by ID on componentDidMount and sends a put request when the form is submitted. I would like to refactor this to a hook based component.
Here is the code before
import React from "react";
import axios from "axios";
//Api Helper Methods
const API_HOST = "https://api.example.com";
const get = (endPoint) =>
axios
.get(`${API_HOST}/${endPoint}`)
.then((response) => response.data);
export const put = (endPoint, payload, id) =>
axios
.put(`${API_HOST}/${endPoint}/${id}`, payload)
.then((response) => response.data);
//React route (uses React Router)
const END_POINT = `users`;
class Entity extends React.Component {
state = { entity: {}, fetching: true };
getEntity = async () => {
const { id } = this.props.match.params;
this.setState({ fetching: true });
const entity = await get(`${END_POINT}/${id}`);
this.setState({ entity, fetching: false });
};
onChange = (key, value) =>
this.setState({ entity: { ...this.state.entity, [key]: value } });
componentDidMount() {
this.getEntity();
}
onSubmit = async (e) => {
e.preventDefault();
let { entity } = this.state;
let { match } = this.props;
await put(END_POINT, entity, match.params.id);
};
render() {
const { entity, fetching } = this.state;
if (fetching) {
return <p>loading...</p>;
}
return (
<form onSubmit={this.onSubmit}>
<label htmlFor="name">name</label>
<input
value={entity["name"]}
onChange={(e) => this.onChange("name", e.target.value)}
/>
<button type="submit">submit</button>
</form>
);
}
}
export default Entity;
This is what I have so far for the code after. Next step would be to extract custom hook.
const END_POINT = `users`;
export default function Entity({ match }) {
const [entity, setEntity] = useState({ name: "" });
const [fetching, setFetching] = useState( true );
const { id } = match.params;
const onChange = (key, value) => setEntity({ ...entity, [key]: value });
useEffect(() => {
const fetchEntity = async () => {
const entity = await get(`${END_POINT}/${id}`);
setEntity(entity);
setFetching(false);
};
fetchEntity();
}, [id]);
const onSubmit = async (e) => {
e.preventDefault();
await put(END_POINT, entity, id);
};
if (fetching) {
return <p>loading...</p>;
}
return (
<form onSubmit={onSubmit}>
<label htmlFor="name">name</label>
<input
value={entity["name"]}
onChange={(e) => onChange("name", e.target.value)}
/>
<button type="submit">submit</button>
</form>
);
}
I haven't tested this but this should be close to what you want with a custom hook for your entity function.
import React, { useEffect, useState } from 'react';
const API_HOST = "https://api.example.com";
const END_POINT = `users`;
function useEntity(entityID) {
const [entity, setEntity] = useState({})
useEffect(() => {
(async () => {
await fetch(`${API_HOST}/${END_POINT}/${props.match.params}`)
.then(async res => await res.json())
.then(result => setEntity(result));
})();
}, [])
return entity
}
export default function Entity(props) {
const { id } = props.match;
const entity = useEntity(id);
const onSubmit = async () => await fetch(`${API_HOST}/${END_POINT}/${id}`, {method: 'PUT', body: entity})
if (!entity) {
return <p>loading...</p>;
}
return (
<form onSubmit={onSubmit}>
<label htmlFor="name">name</label>
<input
value={entity["name"]}
onChange={(e) => setEntity({ ...entity, name: e.target.value})}
/>
<button type="submit">submit</button>
</form>
)
}
Thanks for the help Harben, I got it working like this.
import React, {useEffect, useState} from "react";
import axios from "axios";
//Api Helper Methods
const API_HOST = "https://api.example.com";
const get = (endPoint) =>
axios.get(`${API_HOST}/${endPoint}`).then((response) => response.data);
export const put = (endPoint, payload, id) =>
axios
.put(`${API_HOST}/${endPoint}/${id}`, payload)
.then((response) => response.data);
const END_POINT = `users`;
const useEntity = (entityId) => {
const [entity, setEntity] = useState({ name: "" });
const [fetching, setFetching] = useState(true);
useEffect(() => {
(async () => {
const entity = await get(`${END_POINT}/${entityId}`);
setEntity(entity);
setFetching(false);
})();
}, [entityId]);
return [entity, fetching, setEntity];
};
//React route (uses React Router)
export default function Entity({ match }) {
const { id } = match.params;
const [entity, fetching, setEntity] = useEntity(id);
const onChange = (key, value) => setEntity({ ...entity, [key]: value });
const onSubmit = async (e) => {
e.preventDefault();
await put(END_POINT, entity, id);
};
if (fetching) {
return <p>loading...</p>;
}
return (
<form onSubmit={onSubmit}>
<label htmlFor="name">name</label>
<input
value={entity["name"]}
onChange={(e) => onChange("name", e.target.value)}
/>
<button type="submit">submit</button>
</form>
);
}

redux request failed with status code 400(bad request)

i am getting an error "400 bad request" i can't find out what is my error
below i share my frontend and backend code..
i am also share my image error link that i came
https://ibb.co/swQPgYG
################### backend ######################
todoschema.js
this is a todoschema
var mongoose = require('mongoose');
var todoSchema = new mongoose.Schema({
name: {
type: String,
required: true,
maxlength:32,
trim:true
}
},{timestamps:true}
)
module.exports = mongoose.model('Todo',todoSchema)
auth.js/router
var express = require('express');
var router = express.Router();
const {addTodo} = require('../controller/auth');
router.post('/addtodo',addTodo);
module.exports = router;
auth.js/controller
const Todo = require('../model/todo');
exports.addTodo = (req,res) =>{
const todo = new Todo(req.body)
todo.save((err,todo) => {
if(err || !todo){
return res.status(400).json({
err : 'NOT able to store data in database'
})
}
res.json(todo);
})
}
################## frontEnd ###########################
API == http://localhost:8000/api/
here i fetch request from my backend
index.js
import {API} from '../backend'
import axios from 'axios'
export const getdata = (todo) => {
return (dispatch) => {
axios.post(`${API}addtodo`)
.then(res => {
console.log(res)
dispatch({
type : 'FETCH_TODO',
payload : todo
})
})
.catch(err =>{
console.log(err);
})
}
}
This is the todoForm where i add my todo
todoform.js
import React,{useState, useEffect} from 'react'
import '../App.css'
import {
FormGroup,
Input,
Button,
Form,
InputGroup,
InputGroupAddon
} from 'reactstrap';
import {v4} from 'uuid';
import 'bootstrap/dist/css/bootstrap.min.css';
import {getdata } from '../Auth'
//redux
import {connect, useDispatch} from 'react-redux'
import {addTodo} from '../Action/todo';
const TodoForm = ({addTodo}) => {
const [title,setTitle] = useState('')
const dispatch = useDispatch();
useEffect(() => {
dispatch(getdata())
}, []);
return(
<Form>
<FormGroup>
<InputGroup>
<Input
type='text'
name='todo'
id='todo'
placeholder='Your next Todo'
value={title}
onChange={e => setTitle(e.target.value)}
/>
<InputGroupAddon addonType='prepend'>
<Button color='primary' onClick={()=>{
if(title === ''){
return alert('please add a todo')
}
const todo = {
title,
id:v4(),
}
addTodo(todo);
setTitle('');
}}>
ADD
</Button>
</InputGroupAddon>
</InputGroup>
</FormGroup>
</Form>
)
}
const mapStateToProps = state => ({
})
const mapDispatchToProps = dispatch =>({
addTodo : todo =>{
dispatch(addTodo(todo))
},
})
export default connect(mapStateToProps,mapDispatchToProps)(TodoForm)
getData(todo) - action creator function require argument
export const getdata = (todo) => {
return (dispatch) => {
axios.post(`${API}addtodo`)
.then(res => {
console.log(res)
dispatch({
type : 'FETCH_TODO',
payload : todo
})
})
.catch(err =>{
console.log(err);
})
}
}
and you call it without argument
const dispatch = useDispatch();
useEffect(() => {
dispatch(getdata())
}, []);

Categories