React search by name - reactjs

Hello I am currently fetching through an API call to search by name in my search bar. I'm having an error of whenever I type a string in my search bar.
This is my postman URL /product/list/search?search=assorted where I can fetch names with "assorted"
I'm fetching it in frontend like this
export const searchProducts = async (query) => {
return await get(`product/list/search=?${query})
}
and this is how I implement it on my search page
const SearchPage = () => {
const [products, setProducts] = useState([])
const [query, setQuery] = useState("")
useEffect(() => {
getAllProducts().then((products) => {
setProducts(products)
})
}, [])
useEffect(() => {
const loadProducts = async () => {
const query = await searchProducts(query)
setQuery(query)
}
loadProducts()
}, [query])
return (
<>
<Grid container spacing={3}>
<Grid item xs={1}>
<Box pt={1.5}>
<Link to="#">
<ArrowBackIcon className={classes.backSize} />
</Link>
</Box>
</Grid>
<Grid item xs={11}>
<Paper className={classes.root}>
<IconButton aria-label="menu"></IconButton>
<InputBase
className={classes.input}
placeholder="Search for foods"
onChange={(e) => setQuery(e.target.value)}
value={query}
/>
<IconButton aria-label="search">
<SearchIcon />
</IconButton>
</Paper>
</Grid>
</Grid>
<Box pt={1}>
<CategoryList categories={categories} />
</Box>
<Box pt={1}>
<ProductList products={products} />
</Box>
</>
)
}

Did you try with / at the beginning?
export const searchProducts = async (query) => {
return await get(`/product/list/search?search=${query}`)
}

From what i can see your postman api call and the one in the await doesn't seems to be matching - it should be
await get(`product/list/search?search=${query}`);

Related

React : Error: Rendered fewer hooks than expected. This may be caused by an accidental early return statement

I never see this error before.
I found where error is occurred.
However, i don't know why it occurred.
there is no return code before setState. If i use {imgPath} only, there is no error occurred.
What I do
I create another state for test. If i use state into component, error occurred. It is line 86.
this is my full code
I delete import component code
import { FC, useRef, useState } from 'react';
import styled from 'styled-components';
import { 팀정보변경, uploadLogo } from 'controller/modifyTeam';
import { getTeamInformation } from 'controller/team';
// module
import { useSnackbarStore } from 'module/store/snackbar';
import { useTeamStore } from 'module/store/team';
const Form: FC<Props> = ({ teamname, timezone, id, name, url }) => {
const { updateTeam } = useTeamStore();
const { pushSnackbar } = useSnackbarStore();
const [isEmpty, setIsEmpty] = useState<boolean>(false);
const [imgPath, setImgPath] = useState<string>('');
const [test, setTest] = useState<string>('');
// ref
const teamNameRef = useRef<HTMLInputElement>(null);
const timeLineRef = useRef<HTMLInputElement>(null);
const imgRef = useRef<HTMLInputElement>(null);
const widthSX = (width: string) =>
useSX({
width: `${width}`,
});
const paddingSX = useSX({
padding: '4px 12px !important',
});
// formData
const onClickUploadImage: () => void = () => imgRef?.current?.click();
const onDeleteImage: () => void = () => setImgPath('');
const updateTeamInformation: () => void = async () => {
const res = await getTeamInformation();
updateTeam(res.data.result);
};
const onSubmit: () => void = async () => {
const timeline = timeLineRef.current.value.slice(4, 10).replaceAll(':', '');
const res = await 팀정보변경(teamNameRef.current.value, timeline, imgPath, id);
if (res.data.msg === 'created') {
await updateTeamInformation();
pushSnackbar({
id: 'teamworthchanged',
type: 'Info',
title: `${t('snackbar.team_worth_changed')}`,
});
}
};
const onChangeImage: (event: any) => void = async (event: any) => {
const formData = new FormData();
formData.append('logo', event.target.files[0]);
const res = await uploadLogo(formData);
setImgPath(res.data.result.path);
};
return (
<>
<SideBar index={1} />
<Container>
<Contents xs={12} sm={8} md={6} lg={5}>
<Font className="h5">{t('nav.menu.settings.basic')}</Font>
<WhiteSpace />
<Grid container item xs={12} direction="column">
{/* 기본설정 */}
<Font className="body-2">{t('settings.basic.profile.heading')}</Font>
<Font className="caption">{t('settings.basic.profile.sub')}</Font>
<Grid container flexWrap="wrap" justifyContent="space-between">
<WhiteSpace />
<Grid xs={4} item container alignItems="center">
{imgPath === '' ? (
url === null ? (
<DefaultImg
container
justifyContent="center"
alignItems="center"
sx={widthSX('80px')}
>
{name?.slice(0, 1)}
</DefaultImg>
) : (
<TeamIcon src={url} alt="팀 로고" />
)
) : (
<TeamIcon src={imgPath} alt={'팀 로고'} />
)}
</Grid>
{/* 이미지 업로드 */}
<Grid container item xs="auto" alignItems="center" flexWrap="wrap" sx={UploadImageSX}>
<label htmlFor="contained-button-file">
<MuiButton
content={
<Grid container alignItems="center">
<Grid item>{t('btn.upload_image')}</Grid>
<Grid item>
<MdiIcon width={16} height={16} src="/icons/upload/ic_upload_white.svg" />
</Grid>
</Grid>
}
size="small"
type="contained"
sx={paddingSX}
onClick={onClickUploadImage}
/>
</label>
<ImageInput
accept="image/*"
id="contained-button-file"
onChange={onChangeImage}
type="file"
ref={imgRef}
/>
{/* 이미지 삭제 버튼 */}
<MuiButton
content={t('btn.remove')}
size="small"
color={palette.gray3}
sx={paddingSX}
onClick={onDeleteImage}
/>
</Grid>
</Grid>
</Grid>
<WhiteSpace />
{/* 팀이름 INPUT */}
<Input
label="common.team_name"
isEmpty={isEmpty}
setIsEmpty={setIsEmpty}
ref={teamNameRef}
value={teamname}
/>
<WhiteSpace />
{/* 시간대 */}
<Grid container item xs={12} direction="column">
<Font className="body-2">{t('settings.basic.timezone.heading')}</Font>
<Font className="caption">{t('settings.basic.timezone.sub')}</Font>
</Grid>
<WhiteSpace />
{/* <TimeLine currentTime={timezone} time={time} setTime={setTime} /> */}
<Timeline ref={timeLineRef} time={timezone} />
<WhiteSpace />
<WhiteSpace />
<MuiButton
content={t('btn.save_changes')}
sx={widthSX('100%')}
type="contained"
onClick={onSubmit}
/>
</Contents>
</Container>
</>
);
};
export default Form;

Warning: Each child in a list should have a unique "key" prop; Check the render method of `Post`

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.

Grid of card in material-ui react

Hello I'm trying to create that I had three cards in a row right now one after the other
Can't find a solution
It's a complement
const Posts = ({ setCurrentId }) => {
const fuzzySearch = (list, searchValue) => {
let buf = ".*" + searchValue.replace(/(.)/g, "$1.*").toLowerCase();
var reg = new RegExp(buf);
let newList = list.filter(function (e) {
return reg.test(e.title.toLowerCase()&&e.message);
});
return newList;
};
const [searchValue, setSearchValue] = useState("");
const posts = useSelector((state) => state.posts);
const classes = useStyles();
const [pageNumber, setPageNumber] = useState(1);
const [buttonnext, setbuttonnext] = useState(false);
const [prebutton, setprebutton] = useState(true);
const limit=8;
const [startIndex,setstartIndex] = useState();
const [endIndex,setendIndex] = useState();
useEffect(()=>{
setstartIndex((pageNumber-1)*limit)
setendIndex(pageNumber*limit)
console.log(startIndex)
console.log(endIndex)
},[posts,pageNumber])
const Next = ()=>{
if(pageNumber === (Math.floor((posts.length+limit -1)/limit))){
setbuttonnext(true)
}else{
setPageNumber(pageNumber+1)
setprebutton(false)
}
}
const Previous = () =>{
if(pageNumber === 1){
setprebutton(true)
}else{
setPageNumber(pageNumber-1)
setbuttonnext(false)
}
}
return(
!posts.length ? <CircularProgress /> : <>
< >
<AppBar className={classes.appBar} position="static" color="inherit">
<Typography className={classes.heading} variant="h2" >קבוצות אחרונות</Typography>
<Paper component="form" className={classes.root}>
<IconButton className={classes.iconButton} aria-label="menu">
</IconButton>
<InputBase
className={classes.input}
placeholder="חיפוש "
inputProps={{ 'aria-label': 'search ' }}
value={searchValue}
onChange={(e) => setSearchValue(e.target.value)}
/>
<IconButton className={classes.iconButton} aria-label="search">
<SearchIcon />
</IconButton>
<Divider className={classes.divider} orientation="vertical" />
</Paper>
</AppBar>
<ol>
{fuzzySearch(posts, searchValue).slice(startIndex,endIndex).map((d) => (
<Grid key={d._id} item xs={10} sm={6} md={6}>
<Grow in>
<Post post={d} setCurrentId={setCurrentId} />
</Grow>
</Grid>) )}
</ol>
</>
<Grid className={classes.container} container alignItems="stretch" spacing={3}>
<Grid container direction="row-reverse"justifyContent="center"alignItems="flex-end" >
<>
<button className={classes.button} onClick={Next}>הבא</button>
<p className={classes.numText}>{ pageNumber}</p>
<Button className={classes.button} onClick={Previous}>אחורה</Button>
</>
</Grid>
</Grid></>
)
};
export default Posts;
Then called to app in app.js Grid in shape
return (
<Container maxWidth="lg" >
<Grow in>
<Container>
<Posts setCurrentId={setCurrentId} />
</Container>
</Grow>
</Container>
);
};
export default App;
I would to create a grid that I had three in a row
I don't know what you are trying to achieve, but I assume that you are trying to display 3 cards in a row. The idea is that Material-UI is using flexbox, and they are divided into 12 equal columns.
<Grid spacing={2}>
// Define grid for card items
{
data.map((dataItem) => (
<Grid key={dataItem.id}>
// ... items inside
</Grid>
))
}
</Grid>

Commerce JS API rejecting my test transaction

I'm having a tricky problem. I've created this ecommerce platform with react and I'm using the commerce JS API. I connected my sandbox stripe API key with the sandbox commerce JS key so I could do a test transaction, but each time I get an error and the transaction doesn't go through, leaving my cart quantity unchanged.
In console I get the following error from the commerce JS API:
According to the commerce JS developer setting logs this is the request I'm sending:
{
"line_items": [
{
"id": "item_7RyWOwmK5nEa2V",
"product_id": "prod_LvJjoPJGale0nO",
"name": "Ferrari",
"product_name": "Ferrari",
"media": {
"type": "image",
"source": "https://cdn.chec.io/merchants/28537/assets/o0wPb0EDWAlJnEV1|1.jpg"
},
"sku": null,
"permalink": "kKwz9a",
"quantity": 1,
"price": {
"raw": 1.5,
"formatted": "1.50",
"formatted_with_symbol": "£1.50",
"formatted_with_code": "1.50 GBP"
},
"line_total": {
"raw": 1.5,
"formatted": "1.50",
"formatted_with_symbol": "£1.50",
"formatted_with_code": "1.50 GBP"
},
"is_valid": true,
"product_meta": [],
"tax": {
"is_taxable": false,
"taxable_amount": null,
"amount": null,
"breakdown": null
},
"selected_options": [],
"variant": []
}
],
"customer": [],
"shipping": {
"name": "Primary",
"county_state": "WSM",
"country": "GB"
},
"fulfillment": {
"shipping_method": "ship_RqEv5xvDqwZz4j"
},
"payment": {
"gateway": "stripe",
"stripe": {
"payment_method_id": "pm_1J1FitHjVwDyRBqGNRnw8Ryt"
}
}
}
I don't understand how the email field, shipping address and shipping town/city are missing, as this is what my submission form looks like:
I filled in everything accurately.
Here is my AddressForm component:
import React, { useState, useEffect } from "react";
import {
InputLabel,
Select,
MenuItem,
Button,
Grid,
Typography,
} from "#material-ui/core";
import { useForm, FormProvider } from "react-hook-form";
import { Link } from "react-router-dom";
import { commerce } from "../../lib/commerce";
import FormInput from "./CustomTextField";
const AddressForm = ({ checkoutToken, next }) => {
const [shippingCountries, setShippingCountries] = useState([]);
const [shippingCountry, setShippingCountry] = useState("");
const [shippingSubdivisions, setShippingSubdivisions] = useState([]);
const [shippingSubdivision, setShippingSubdivision] = useState("");
const [shippingOptions, setShippingOptions] = useState([]);
const [shippingOption, setShippingOption] = useState("");
const methods = useForm();
const fetchShippingCountries = async (checkoutTokenId) => {
const { countries } = await commerce.services.localeListShippingCountries(
checkoutTokenId
);
setShippingCountries(countries);
setShippingCountry(Object.keys(countries)[0]);
};
const fetchSubdivisions = async (countryCode) => {
const { subdivisions } = await commerce.services.localeListSubdivisions(
countryCode
);
setShippingSubdivisions(subdivisions);
setShippingSubdivision(Object.keys(subdivisions)[0]);
};
const fetchShippingOptions = async (
checkoutTokenId,
country,
region = null
) => {
const options = await commerce.checkout.getShippingOptions(
checkoutTokenId,
{ country, region }
);
setShippingOptions(options);
setShippingOption(options[0].id);
};
useEffect(() => {
fetchShippingCountries(checkoutToken.id);
}, []);
useEffect(() => {
if (shippingCountry) fetchSubdivisions(shippingCountry);
}, [shippingCountry]);
useEffect(() => {
if (shippingSubdivision)
fetchShippingOptions(
checkoutToken.id,
shippingCountry,
shippingSubdivision
);
}, [shippingSubdivision]);
return (
<>
<Typography variant="h6" gutterBottom>
Shipping address
</Typography>
<FormProvider {...methods}>
<form
onSubmit={methods.handleSubmit((data) =>
next({
...data,
shippingCountry,
shippingSubdivision,
shippingOption,
})
)}
>
<Grid container spacing={3}>
<Grid item xs={12} sm={6}>
<FormInput required name="firstName" label="First name" />{" "}
</Grid>
<Grid item xs={12} sm={6}>
{" "}
<FormInput required name="lastName" label="Last name" />
</Grid>
<Grid item xs={12} sm={6}>
{" "}
<FormInput required name="address1" label="Address line 1" />
</Grid>
<Grid item xs={12} sm={6}>
{" "}
<FormInput required name="email" label="Email" />
</Grid>
<Grid item xs={12} sm={6}>
{" "}
<FormInput required name="city" label="City" />
</Grid>
<Grid item xs={12} sm={6}>
{" "}
<FormInput required name="zip" label="Zip / Postal code" />
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>Shipping Country</InputLabel>
<Select
value={shippingCountry}
fullWidth
onChange={(e) => setShippingCountry(e.target.value)}
>
{Object.entries(shippingCountries)
.map(([code, name]) => ({ id: code, label: name }))
.map((item) => (
<MenuItem key={item.id} value={item.id}>
{item.label}
</MenuItem>
))}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>Shipping Subdivision</InputLabel>
<Select
value={shippingSubdivision}
fullWidth
onChange={(e) => setShippingSubdivision(e.target.value)}
>
{Object.entries(shippingSubdivisions)
.map(([code, name]) => ({ id: code, label: name }))
.map((item) => (
<MenuItem key={item.id} value={item.id}>
{item.label}
</MenuItem>
))}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>Shipping Options</InputLabel>
<Select
value={shippingOption}
fullWidth
onChange={(e) => setShippingOption(e.target.value)}
>
{shippingOptions
.map((sO) => ({
id: sO.id,
label: `${sO.description} - (${sO.price.formatted_with_symbol})`,
}))
.map((item) => (
<MenuItem key={item.id} value={item.id}>
{item.label}
</MenuItem>
))}
</Select>
</Grid>
</Grid>
<br />
<div style={{ display: "flex", justifyContent: "space-between" }}>
<Button component={Link} variant="outlined" to="/cart">
Back to Cart
</Button>
<Button type="submit" variant="contained" color="primary">
Next
</Button>
</div>
</form>
</FormProvider>
</>
);
};
export default AddressForm;
My payment form component:
import React from "react";
import { Typography, Button, Divider } from "#material-ui/core";
import {
Elements,
CardElement,
ElementsConsumer,
} from "#stripe/react-stripe-js";
import { loadStripe } from "#stripe/stripe-js";
import Review from "./Review";
const stripePromise = loadStripe(process.env.REACT_APP_STRIPE_PUBLIC_KEY);
const PaymentForm = ({
checkoutToken,
nextStep,
backStep,
shippingData,
onCaptureCheckout,
}) => {
const handleSubmit = async (event, elements, stripe) => {
event.preventDefault();
if (!stripe || !elements) return;
const cardElement = elements.getElement(CardElement);
const { error, paymentMethod } = await stripe.createPaymentMethod({
type: "card",
card: cardElement,
});
if (error) {
console.log("[error]", error);
} else {
const orderData = {
line_items: checkoutToken.live.line_items,
customer: {
firstname: shippingData.firstName,
lastname: shippingData.lastName,
email: shippingData.email,
},
shipping: {
name: "Primary",
street: shippingData.address1,
town_city: shippingData.city,
county_state: shippingData.shippingSubdivision,
postal_zip_code: shippingData.zip,
country: shippingData.shippingCountry,
},
fulfillment: { shipping_method: shippingData.shippingOption },
payment: {
gateway: "stripe",
stripe: {
payment_method_id: paymentMethod.id,
},
},
};
onCaptureCheckout(checkoutToken.id, orderData);
nextStep();
}
};
return (
<>
<Review checkoutToken={checkoutToken} />
<Divider />
<Typography variant="h6" gutterBottom style={{ margin: "20px 0" }}>
Payment method
</Typography>
<Elements stripe={stripePromise}>
<ElementsConsumer>
{({ elements, stripe }) => (
<form onSubmit={(e) => handleSubmit(e, elements, stripe)}>
<CardElement />
<br /> <br />
<div style={{ display: "flex", justifyContent: "space-between" }}>
<Button variant="outlined" onClick={backStep}>
Back
</Button>
<Button
type="submit"
variant="contained"
disabled={!stripe}
color="primary"
>
Pay {checkoutToken.live.subtotal.formatted_with_symbol}
</Button>
</div>
</form>
)}
</ElementsConsumer>
</Elements>
</>
);
};
export default PaymentForm;
And also my APP JS:
import React, { useState, useEffect } from "react";
import { Products, Navbar, Cart, Checkout } from "./components";
import { commerce } from "./lib/commerce";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";
const App = () => {
const [products, setProducts] = useState([]);
const [cart, setCart] = useState({});
const [order, setOrder] = useState({});
const [errorMessage, setErrorMessage] = useState("");
const fetchProducts = async () => {
const { data } = await commerce.products.list();
setProducts(data);
};
const fetchCart = async () => {
setCart(await commerce.cart.retrieve());
};
const handleAddToCart = async (productId, quantity) => {
const { cart } = await commerce.cart.add(productId, quantity);
setCart(cart);
};
const handleUpdateCartQty = async (productId, quantity) => {
const { cart } = await commerce.cart.update(productId, { quantity });
setCart(cart);
};
const handleRemoveFromCart = async (productId) => {
const { cart } = await commerce.cart.remove(productId);
setCart(cart);
};
const handleEmptyCart = async () => {
const { cart } = await commerce.cart.empty();
setCart(cart);
};
const refreshCart = async () => {
const newCart = await commerce.cart.refresh();
console.log(newCart);
setCart(newCart);
};
const handleCaptureCheckout = async (checkoutTokenId, newOrder) => {
try {
const incomingOrder = await commerce.checkout.capture(
checkoutTokenId,
newOrder
);
setOrder(incomingOrder);
refreshCart();
} catch (error) {
setErrorMessage(error.data.error.message);
}
};
useEffect(() => {
fetchProducts();
fetchCart();
}, []);
return (
<Router>
<div>
<Navbar totalItems={cart.total_items} />
<Switch>
<Route exact path="/">
<Products products={products} onAddToCart={handleAddToCart} />
</Route>
<Route exact path="/cart">
<Cart
cart={cart}
handleUpdateCartQty={handleUpdateCartQty}
handleRemoveFromCart={handleRemoveFromCart}
handleEmptyCart={handleEmptyCart}
/>
</Route>
<Route exact path="/checkout">
<Checkout
cart={cart}
order={order}
onCaptureCheckout={handleCaptureCheckout}
error={errorMessage}
/>
</Route>
</Switch>
</div>
</Router>
);
};
export default App;
I spoke to some people on the Commerce JS slack and they pointed out that these fields were 'missing' but I don't understand what they mean by that. I've read that others have had this issue too (specifically people following this tutorial: https://www.youtube.com/watch?v=377AQ0y6LPA) so I'm not sure if it's a problem with the code or the API.
I'm at a loss here so I'd really appreciate any help or suggestions.
Thanks
Console log ur shipping data and check if the names of the objects are the same
for example if : shippingData has the email stored in Email instead of email.So Payment Form cannot recognize the information
in your FormInput component check that you use render instead of as props and try to spread param of callback inside ex:
<Controller control={control}
name={name}
render={({field})=>(<TextField
label={label}
{...field}
required={required}
fullWidth
value={field.value}
/>)}
/>

Can't send post request to authenticate user in react & redux

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/

Resources