so I'm getting these Errors out of nowhere, I worked with the code yesterday and everything was fine.
This is like a social Media platform and
yesterday I could display the Posts, and today I can't. I can still take pictures and save it in the Firebase DB that works fine but it won't post itself at the feed.
This is the Code:
function Profile(props) {
const classes = useStyles();
const [reason, setReason] = React.useState('');
const [open, setOpen] = React.useState(false);
const handleChange = (event) => {
setReason(event.target.value);
};
const handleClose = () => {
setOpen(false);
};
const handleOpen = () => {
setOpen(true);
};
const [userPosts, setUserPosts] = useState([]);
const [user, setUser] = useState(null);
const [following, setFollowing] = useState(false)
useEffect(() => {
const { currentUser, posts } = props;
console.log({ currentUser, posts });
if (props.route.params.uid === firebase.auth().currentUser.uid) {
setUser(firebase.auth().currentUser);
setUserPosts(posts);
}else{
firebase.firestore()
.collection("users")
.doc(props.route.params.uid)
.get()
.then((snapshot) =>{
if(snapshot.exists){
setUser(snapshot.data())
}else{
console.log('does not exist')
}
})
firebase.firestore()
.collection("posts")
.doc(props.route.params.uid)
.collection("userPosts")
.orderBy("creation", "asc")
.get()
.then((snapshot) =>{
let posts = snapshot.docs.map(doc => {
const data = doc.data();
const id = doc.id;
return{id, ...data}
})
setUserPosts(posts)
})
}
if(props.following.indexOf(props.route.params.uid) > -1){
setFollowing(true);
}else{
setFollowing(false)
}
},[props.route.params.uid, props.following]);
const onFollow = () =>{
firebase.firestore()
.collection("following")
.doc(firebase.auth().currentUser.uid)
.set({
following : [props.route.params.uid]
})
}
const onLogout = () =>{
firebase.auth().signOut();
}
if (user === null) {
return <View />;
}
return (
<div className={classes.div}>
<div >
<Avatar alt="Ana Pädagogin" className={classes.avatar} />
<Typography className={classes.text} > {user.name} </Typography>
<Typography className={classes.text} > {user.email} </Typography>
{props.route.params.uid !== firebase.auth().currentUser.uid ? (
<Container>
{following ? (
<Button
className={classes.btn}
size="large"
variant="outlined"
onClick={() => onUnFollow()}
>Following</Button>
) :
(
<Button
className={classes.btn}
size="large"
variant="outlined"
onClick={() => onFollow()}
>Follow</Button>
)}
</Container>
) : <Button
className={classes.btn}
size="large"
variant="outlined"
onClick={() => onLogout()}
>Logout</Button>}
<Card>
{/* //Verspätung */}
<CardContent>
<Typography variant="h5" className={classes.cardTyp}> Verspätung </Typography>
<Container className={classes.cardContainer}>
<TextField
id="time"
label="Zeit"
type="time"
className={classes.cardTime}
defaultValue="07:30"
InputLabelProps={{
shrink: true,
}}
inputProps={{
step: 300, // 5 min
}}
/>
<Button className={classes.cardBtn}>Absenden</Button>
</Container>
</CardContent>
{/* //Krankenmledungen */}
<CardContent className={classes.cardKrankmeldung}>
<Typography variant="h5" className={classes.cardTyp}> Krankenmledungen </Typography>
<Container className={classes.cardContainer}>
<TextField
id="date"
label="Von"
type="date"
defaultValue="2017-05-24"
className={classes.textField}
InputLabelProps={{
shrink: true,
}}
/>
<TextField
id="date"
label="bis"
type="date"
defaultValue="2017-05-24"
className={classes.textField}
InputLabelProps={{
shrink: true,
}}
/>
</Container>
<Button className={classes.cardBtn}>Absenden</Button>
</CardContent>
{/* //Verspätung Abolung*/}
<CardContent>
<Typography variant="h5" className={classes.cardTyp}> Verspätung Abholung</Typography>
<Container className={classes.cardContainer}>
<TextField
id="time"
label="Zeit"
type="time"
defaultValue="07:30"
InputLabelProps={{
shrink: true,
}}
inputProps={{
step: 300, // 5 min
}}
/>
<Button className={classes.cardBtn}>Absenden</Button>
</Container>
</CardContent>
</Card>
</div>
</div>
)
}
const mapStateToProps = (store) => ({
currentUser: store.userState.currentUser,
posts: store.userState.posts,
following: store.userState.following
});
export default connect(mapStateToProps, null)(Profile);
As Frank van Puffelen pointed out your problem lies in Firebase Firestore security rules.
If you can save post on db, it seems that you have write permission but not read permission on that collection.
You can test how changing security rules affect this problem by first enabling all reads and writes to that collection
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /yourCollectionName/{ID}{
allow read, write: if true;
}
}
}
, and then restricting the collection as you need.
Check these guides to apply needed modifications and best practices to your security rules.
https://firebase.google.com/docs/firestore/security/get-started
https://firebase.google.com/docs/firestore/security/rules-structure
Related
I have a React+ Rails app .I am facing a small prob with my react application. Whenever I make a post request I am navigated to a page,but I cannot see my card rendered.After I refresh the page I can see the card getting rendered AND it ever persists on the page .Why do I have to refresh the page though?How to solve this?
Here is my code.I have added some MUI designing pardon me if thats confusing
Reservation Form
function ReservationForm() {
const navigate = useNavigate();
const params = useParams();
const { user,errors,setErrors } = useContext(Cont);
const [reservationData, setReservationData] = useState({
name: "",
date: "",
time: "",
num: "",
contact: "",
occasion: "",
});
function handleReservationChange(event) {
setReservationData({
...reservationData,
[event.target.name]: event.target.value,
});
}
function handleReservationChangeWithNameAndValue(name, newValue) {
setReservationData({
...reservationData,
[name]: newValue,
});
}
function handleReservationSubmit(event) {
event.preventDefault();
const newReservation = {
...reservationData,
restaurant_id: params.id,
user_id: user.id,
};
fetch(`/reservations`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(newReservation),
})
.then((r) => r.json())
.then(
setReservationData({
name: "",
date: "",
time: "",
num: "",
contact: "",
occasion: "",
})
);
navigate("/myreservations");
}
return (
<>
<div className="overlay3">
<Box
component="form"
sx={{
"& > :not(style)": { m: 1 },
}}
noValidate
autoComplete="off"
onSubmit={handleReservationSubmit}
>
<h1 className="editheadings">Reserve 🍽️</h1>
<FormControl className="inputstyle">
<InputLabel htmlFor="component-outlined">Name</InputLabel>
<OutlinedInput
type="text"
name="name"
id="name"
value={reservationData.name}
onChange={handleReservationChange}
label="Name"
/>
</FormControl>
<br />
<FormControl name="date" className="inputstyle">
<LocalizationProvider
dateAdapter={AdapterDayjs}
name="date"
fullWidth
>
<DatePicker
label="Date"
name="date"
value={reservationData.date || null}
onChange={(newVal) =>
handleReservationChangeWithNameAndValue("date", newVal)
}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
</FormControl>
<FormControl className="inputstyle">
<LocalizationProvider dateAdapter={AdapterDayjs}>
<TimePicker
name="time"
label="Time"
value={reservationData.time || null}
onChange={(newVal) =>
handleReservationChangeWithNameAndValue("time", newVal)
}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
</FormControl>
<br />
<FormControl className="inputstyle">
<InputLabel htmlFor="component-outlined">No. of Guests</InputLabel>
<OutlinedInput
type="number"
name="num"
value={reservationData.num}
onChange={handleReservationChange}
/>
</FormControl>
<br />
<FormControl className="inputstyle">
<InputLabel htmlFor="component-outlined">Contact</InputLabel>
<OutlinedInput
type="tel"
name="contact"
value={reservationData.contact}
onChange={handleReservationChange}
placeholder="contact"
/>
</FormControl>
<br />
<FormControl className="inputstyle">
<InputLabel htmlFor="component-outlined">Occasion</InputLabel>
<OutlinedInput
type="text"
name="occasion"
value={reservationData.occasion}
onChange={handleReservationChange}
/>
</FormControl>
<Stack paddingLeft={15} direction="row" id="loginbutton">
<ColorButton variant="contained" type="submit">
{" "}
Reserve
</ColorButton>
</Stack>
</Box>
</div>
</>
);
}
export default ReservationForm;
My Reservations
import {useEffect, useState } from "react";
import ReservationCard from "./ReservationCard";
import { useContext } from "react";
import { Cont } from "../Cont";
function MyReservations(){
const {reservations,setReservations}=useContext(Cont);
useEffect(()=>{
fetch("/reservations")
.then(res=>res.json())
.then(reservationData=>{
setReservations(reservationData)
})
},[])
function handleUpdateReservation(updatedReservation) {
const updatedReservations = reservations.map((reservation) => {
if (reservation.id === updatedReservation.id) {
return updatedReservation;
} else {
return reservation;
}
});
setReservations(updatedReservations);
}
function handleCancel(reservationtodelete){
const newReservations=reservations.filter(r=>r.id !== reservationtodelete)
setReservations(newReservations)
}
const renderReservations=reservations.map((reservation)=>(
<ReservationCard key={reservation.id} reservation={reservation} handleCancel={handleCancel} onUpdateReservation={handleUpdateReservation} />
))
return(
<>
{renderReservations}
</>
)
}
export default MyReservations;
Reservation Card
function ReservationCard({ reservation, handleCancel, onUpdateReservation }) {
const { name, date, time, num, contact, occasion } = reservation;
const [isEditing, setIsEditing] = useState(false);
const handleReservationUpdate = (updatedReservation) => {
setIsEditing(false);
onUpdateReservation(updatedReservation);
};
function handleDeleteClick() {
fetch(`/reservations/${reservation.id}`, {
method: "DELETE",
});
handleCancel(reservation.id);
}
return (
<>
{isEditing ? (
<Box m={4} sx={{ width: 500 }}>
<div className="overlay2">
<EditReservationForm
reservation={reservation}
onUpdateReservation={handleReservationUpdate}
/>
</div>
</Box>
) : (
<>
<Box m={4} sx={{ width: 500 }}>
<Card width={5}>
<CardContent>
<Typography variant="h5" component="div">
{reservation.restaurant.name}
</Typography>
<br />
<Typography sx={{ mb: 1.5 }} color="text.secondary">
Guest Details
</Typography>
<Typography variant="h6" component="div">
{name}
</Typography>
<Typography variant="h6">{contact}</Typography>
<Typography variant="h6">Date:{date}</Typography>
<Typography variant="h6">Time : {time}</Typography>
<Typography variant="h6">Guests : {num}</Typography>
<Typography variant="h6">Occasion:{occasion}</Typography>
</CardContent>
<CardActions>
<Button onClick={() => setIsEditing((isEditing) => !isEditing)}>
{" "}
Modify Booking
</Button>
<Button onClick={handleDeleteClick}>Cancel Booking</Button>
</CardActions>
</Card>
</Box>
</>
)}
</>
);
}
export default ReservationCard;
Fetch is an async promise function, so you'd need to use .then or await to make sure to receive the response.
const response = await fetch(
`http://localhost:8080/api/user/login?username=${uname}&password=${pass}`, {
method: 'POST'
}
);
const userData = await response.json();
when I click by tag, it works fine, but when I click creators, it just return "No posts".
I check the console, and there's an error says the key in list should be unique. Why this happens? Since searchbytag works, does this mean the render method of 'Post' is fine?
updated code
import axios from 'axios';
const API = axios.create({ baseURL: 'http://localhost:5000' });
API.interceptors.request.use((req) => {
if (localStorage.getItem('profile')) {
req.headers.Authorization = `Bearer
${JSON.parse(localStorage.getItem('profile')).token}`;
}
return req;
});
export const createPost = (newPost) => API.post('/posts', newPost);
const Post = ({ post, setCurrentId }) => {
const user = JSON.parse(localStorage.getItem('profile'));
const [likes, setLikes] = useState(post?.likes);
const dispatch = useDispatch();
const history = useHistory();
const classes = useStyles();
const userId = user?.result?._id;
const hasLikedPost = post.likes.find((like) => like === userId);
const handleLike = async () => {
dispatch(likePost(post._id));
if (hasLikedPost) {
setLikes(post.likes.filter((id) => id !== userId));
} else {
setLikes([...post.likes, userId]);
}
};
const Likes = () => {
if (likes.length > 0) {
return likes.find((like) => like === userId)
? (
<><ThumbUpAltIcon fontSize="small" /> {likes.length > 2 ? `You and ${likes.length - 1} others` : `${likes.length} like${likes.length > 1 ? 's' : ''}`}</>
) : (
<><ThumbUpAltOutlined fontSize="small" /> {likes.length} {likes.length === 1 ? 'Like' : 'Likes'}</>
);
}
return <><ThumbUpAltOutlined fontSize="small" /> Like</>;
};
const openPost = (e) => {
// dispatch(getPost(post._id, history));
history.push(`/posts/${post._id}`);
};
return (
<Card className={classes.card} raised elevation={6}>
<ButtonBase
component="span"
name="test"
className={classes.cardAction}
onClick={openPost}
>
<CardMedia className={classes.media} image={post.selectedFile || 'https://user-images.githubusercontent.com/194400/49531010-48dad180-f8b1-11e8-8d89-1e61320e1d82.png'} title={post.title} />
<div className={classes.overlay}>
<Typography variant="h6">{post.name}</Typography>
<Typography variant="body2">{moment(post.createdAt).fromNow()}</Typography>
</div>
{(user?.result?._id === post?.creator) && (
<div className={classes.overlay2} name="edit">
<Button
onClick={(e) => {
e.stopPropagation();
setCurrentId(post._id);
}}
style={{ color: 'white' }}
size="small"
>
<MoreHorizIcon fontSize="default" />
</Button>
</div>
)}
<div className={classes.details}>
<Typography variant="body2" color="textSecondary" component="h2">{post.tags.map((tag) => `#${tag} `)}</Typography>
</div>
<Typography className={classes.title} gutterBottom variant="h5" component="h2">{post.title}</Typography>
<CardContent>
<Typography variant="body2" color="textSecondary" component="p">{post.message.split(' ').splice(0, 20).join(' ')}...</Typography>
</CardContent>
</ButtonBase>
<CardActions className={classes.cardActions}>
<Button size="small" color="primary" disabled={!user?.result} onClick={handleLike}>
<Likes />
</Button>
{(user?.result?._id === post?.creator) && (
<Button size="small" color="secondary" onClick={() => dispatch(deletePost(post._id))}>
<DeleteIcon fontSize="small" /> Delete
</Button>
)}
</CardActions>
</Card>
);
};
export default Post;
Here's my code
const CreatorOrTag = () => {
const { name } = useParams();
const dispatch = useDispatch();
const { posts, isLoading } = useSelector((state) => state.posts);
const location = useLocation();
useEffect(() => {
if (location.pathname.startsWith('/creators')) {
dispatch(getPostsByCreator({ name: name }));
}
else {
dispatch(getPostsBySearch({ tags: name }));
}
}, []);
if (!posts.length && !isLoading) return 'No posts';
return (
<div>
<Typography variant="h2">{name}</Typography>
<Divider style={{ margin: '20px 0 50px 0' }} />
{isLoading ? <CircularProgress /> : (
<Grid container alignItems="stretch" spacing={3}>
{posts?.map((post) => (
<Grid key={post._id} item xs={12} sm={12} md={6} lg={3}>
<Post post={post} />
</Grid>
))}
</Grid>
)}
</div>
);
};
export default CreatorOrTag;
What this warning indicates is that the value you're providing for key is the same in at least two items of the array. I'd put money on the _id property for at least two of them being null or undefined.
Hey i cant find a solution why my code dosent work. When i trigger the button nothing happens, normally i want to display the data but nothing happend. My Code is in attachment.
if someone has an idde to solve the problem I would be very grateful.
I have looked at other posts but nothing helps with my Problem.
export default function FormDialog(props) {
const [open, setOpen] = React.useState(false);
const {
control,
formState: { errors },
setValue,
} = useFormContext();
let isError = false;
let errorMessage = "";
if (errors && errors.hasOwnProperty(name)) {
isError = true;
errorMessage = errors[name].message;
}
const handleClickOpen = () => {
setOpen(true);
};
const handleClose = () => {
setOpen(false);
props.func();
};
const handleChange = (event) => {
props.setMenge(event.target.value);
};
React.useEffect(() => {
if (errors) {
console.log(errors);
}
}, [errors]);
return (
<>
<Button variant="contained" onClick={handleClickOpen}>
Umbuchen
</Button>
<Dialog open={open} onClose={handleClose}>
<DialogTitle>Umbuchung</DialogTitle>
<DialogContent>
<DialogContentText>
Bitte geben Sie die Menge ein die umgelagert werden soll!
</DialogContentText>
<Controller
control={control}
name={props.name}
render={({ field }) => (
<TextField
{...field}
label={props.label}
error={isError}
helperText={errorMessage}
autoFocus
margin="dense"
id="menge"
type="number"
fullWidth
variant="standard"
/>
)}
/>
</DialogContent>
<DialogActions>
<Button onClick={handleClose}>Schließen</Button>
<Button variant="contained" color="primary" type="submit">
Umbuchen
</Button>
</DialogActions>
</Dialog>
</>
);
}
export default function Home() {
const [sEingang, setSEingang] = useState([]);
const [sLager, setSLager] = useState("");
const [menge, setMenge] = useState(0);
const context = React.useContext(AuthContext);
const { data: warendata } = useWaren(context.access_token);
const { data: lagerdata } = useGetLager(context.access_token);
const methods = useForm({
resolver: yupResolver(validationShema),
mode: "all",
});
const { getValues, reset, watch, handleSubmit } = methods;
const waren = watch("selWaren");
const { data: chargendata, refetch } = useChargen({
access_token: context.access_token,
lager: waren,
});
const { mutateAsync, isError: mutError, isLoading, isSuccess } = useAnlegen();
React.useEffect(() => {
async function getToken() {
const res = await context.setTokenSilently();
}
const interval = setInterval(() => {
getToken();
}, 30000);
return () => clearInterval(interval);
}, []);
const onSubmit = (data) => {
console.log("data: ", data);
};
return (
<>
<CssBaseline />
<ButtonAppBar name={"Wareneingänge"} back={false} onClick={reset} />
<FormProvider {...methods}>
<form onSubmit={handleSubmit(onSubmit)}>
<Grid
container
spacing={0}
direction="column"
alignItems="center"
justifyContent="center"
sx={{p: 2, m: 3}}
style={{ minHeight: "50vh", }}
>
<Grid item xs={3}>
<MySelect
formname={"selWaren"}
data={warendata}
name={"Wareneingänge"}
selected={sEingang}
setSelected={setSEingang}
reset={reset} />
</Grid>
<Grid item xs={3}>
<MySelect
formname={"selLager"}
data={lagerdata}
name={"Freie Lagerplätze"}
selected={sLager}
setSelected={setSLager} />
</Grid>
<Grid item xs={3}>
<MySelect
formname={"selChargen"}
data={chargendata}
name={"Freie Chargenplätze"}
selected={sLager}
setSelected={setSLager} />
</Grid>
<Grid item xs={3} sx={{ m: 3}}>
<FormDialog
func={onSubmit}
name={"selMenge"} />
</Grid>
</Grid>
</form>
</FormProvider>
</>
);
}
It looks like you've forgotten to add an onClick handler for the submit button here:
<Button variant="contained" color="primary" type="submit">
Umbuchen
</Button>
Something like this should work:
<Button onClick={() => props.func()} variant="contained" color="primary" type="submit">
Umbuchen
</Button>
I have the following component:
export default function SignIn() {
const [isLoading, setIsLoading] = useState(false);
const classes = useStyles();
const handleSubmit = (event) => {
event.preventDefault();
if(!AuthService.login(event.target))
{
setIsLoading(false);
}
}
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form} noValidate onSubmit={(event) => { handleSubmit(event); setIsLoading(true); }}>
{ isLoading ?
<CircularProgress/> :
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
}
</form>
</div>
</Container>
);
}
When I submit the form, the "isLoading" becomes true, and the loading bars show up. Anyway if the "AuthService.login()" fails, the "isLoading" state is not updated.
What am I doing wrong?
Working code
The problem was related to the fact that
if(!AuthService.login(event.target))
is an async function, so I had to "await" for the response in order to evaluate it's result.
The working code:
async function handleSubmit (event) {
event.preventDefault();
setIsLoading(true)
try {
await AuthService.login(event.target);
setIsLoading(false)
} catch (e) {
console.log('Handle errors here');
} finally {
console.log('We do cleanup here');
}
}
Change:
onSubmit={(event) => { handleSubmit(event); setIsLoading(true); }}
to:
onSubmit={(event) => { handleSubmit(event) }}
Also change handleSubmit to:
const handleSubmit = (event) => {
event.preventDefault();
setLoading(true);
if(!AuthService.login(event.target))
{
setIsLoading(false);
}
}
you are always setting isLoading to true in onSubmit
export default function SignIn() {
const [isLoading, setIsLoading] = useState(false);
const classes = useStyles();
const handleSubmit = (event) => {
event.preventDefault();
setLoading(true)
if(!AuthService.login(event.target))
{
setIsLoading(false);
}
}
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form className={classes.form} noValidate onSubmit={(event) => { handleSubmit(event) }}>
{ isLoading ?
<CircularProgress/> :
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
}
</form>
</div>
</Container>
);
}
I have implemented all of actions and want to call that action with username and password parameters to authenticate user in form.But when I click submit no request is being sended and nothing happens.Code is a little bit long so I'm gonna cut the main part.
actions.js
const authStart = () => {
return {
type: "AUTH_START",
};
};
const authSucceed = (token) => {
return {
type: "AUTH_SUCCESS",
payload: token,
};
};
const authFailed = (error) => {
return {
type: "AUTH_FAILED",
payload: error,
};
};
export const authLogin = (username, password) => {
return (dispatch) => {
dispatch(authStart());
axios
.post("http://127.0.0.1:8000/rest-auth/login/", {
username: username,
password: password,
})
.then((res) => {
const token = res.data.key;
dispatch(authSucceed(token));
})
.catch((err) => {
dispatch(authFailed(err));
});
};
};
SignIn.js
const SignIn = (props) => {
const classes = useStyles();
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
// const [username,setUsername] = useState("")
// const [password,setPassword] = useState("")
const submitHandler = (e) => {
e.preventDefault();
props.onAuth(username,password)
setUsername("");
setPassword("");
};
return (
<Container component="main" maxWidth="xs">
<CssBaseline />
<div className={classes.paper}>
<Avatar className={classes.avatar}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Sign in
</Typography>
<form onSubmit={submitHandler} className={classes.form} noValidate>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
id="username"
label="Username"
name="username"
autoComplete="username"
autoFocus
onChange={(e) => setUsername(e.target.value)}
/>
<TextField
variant="outlined"
margin="normal"
required
fullWidth
name="password"
label="Password"
type="password"
id="password"
autoComplete="current-password"
onChange={(e) => setPassword(e.target.value)}
/>
<FormControlLabel
control={<Checkbox value="remember" color="primary" />}
label="Remember me"
/>
<Button
type="submit"
fullWidth
variant="contained"
color="primary"
className={classes.submit}
>
Sign In
</Button>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Forgot password?
</Link>
</Grid>
<Grid item>
<Link to="/signup" variant="body2">
{"Don't have an account? Sign Up"}
</Link>
</Grid>
</Grid>
</form>
</div>
<Box mt={8}>
<Copyright />
</Box>
</Container>
);
};
const mapStateToProps = state => {
return state.Auth
}
const mapDispatchToProps = dispatch => {
return {
onAuth: (username,password) => {authLogin(username,password)}
}
}
export default connect(mapStateToProps,mapDispatchToProps)(SignIn);
I'll be grateful if you help me out with this.Thanks
Looking at the way your code is setup, authLogin returns a function which takes dispatch as a param, so you probably need to do:
onAuth: (username,password) => {authLogin(username,password)(dispatch)}
You could use bindActionCreators() as well to return the dispatch function, in the following way:-
const mapDispatchToProps = (dispatch) => {
return {
actions: bindActionCreators(authLogin(username,password), dispatch)
}
}
If you want another way to do the same, you could refer to the link below.
https://blog.logrocket.com/react-redux-connect-when-and-how-to-use-it-f2a1edab2013/