Skip to content

Instantly share code, notes, and snippets.

@basir
Last active April 14, 2021 05:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save basir/468f541ccda6b88e7efec99b1658db37 to your computer and use it in GitHub Desktop.
Save basir/468f541ccda6b88e7efec99b1658db37 to your computer and use it in GitHub Desktop.

PayPal Zoid Error

the issue is because of loading PayPal script multiple times.

try placing orders on the demo website at https://proshopapp.herokuapp.com/

You will not get this error. Please clone this repo and run it on your computer. It works.

https://github.com/bradtraversy/proshop_mern/

Then compare your code with this.

Error: The uri parameter to openUri() must be a string, got "undefined".

Make sure you .env file in project folder and it has: MONGO_URI = your mongodb uri If you install mongodb locally the uri is "mongodb://localhost/proshop" Read more: https://github.com/bradtraversy/proshop_mern/#env-variables

ENOENT: no such file or directory, stat '/frontend/build/index.html'

It means you did not create build folder in frontend. check on local by doing this:

$ cd frontend

$ npm build

then go back to root:

$ cd ..

$ npm start

Uncaught Error: Element type is invalid: expected a string

It means the value is going to render in the screen is null or is js object. you need to console.log the value before return statement in the component to check its value and find when it gets null. another simple way to fix this issue is to clone this repo and run it on your computer. It works.

https://github.com/bradtraversy/proshop_mern/

Then compare your code with this.

ERR! Cannot read property 'length' of undefined

When you get this error you need to check the value before .length and use console.log to see why it is null. then compare your code with repo to find the mistake in the code.

https://github.com/bradtraversy/proshop_mern/

Page keeps showing loader without loading content

Check the loading value in the Redux dev tools and see which actions change its value. For better debug please clone this repo and run it on your computer. It works.

https://github.com/bradtraversy/proshop_mern/

Then compare your code with this.

SyntaxError: Unexpected token import

make sure you have "type":"module" in package.json like this:

https://github.com/bradtraversy/proshop_mern/blob/master/package.json#L6

Also you can use --experimental-modules parameter for node older than 13

Error: no file or directory, open 'tmp/buildxxx/frontend/package.json

the error says it can not find the package.json in the frontend folder.

check if you have .git folder in the frontend folder and delete it. then commit and push heroku.

if it does not work then clone this repo and run it on your computer. It works.

https://github.com/bradtraversy/proshop_mern/

Then compare your code with this.

TypeError: product is undefined

check redux devtools to see if you have data for product in the productDetails state.

you need to see action and reducer for detailsProduct and also the backend for /api/product/:id for this issue.

you can clone this repo and run it on your computer. It works.

https://github.com/bradtraversy/proshop_mern/

Then compare your code with this.

What Is Service Worker

it is for PWA apps. we are going to make a PWA in this course.

read more: https://create-react-app.dev/docs/making-a-progressive-web-app/

auto format save

Install ESlint and Prettier Extension and set auto save on vs code setting.

  "editor.formatOnSave": true,
  "javascript.format.enable": false,
  "editor.codeActionsOnSave": {
    "source.fixAll.eslint": true
  },

EADDRINUSE : address already in use

Restart VS Code and close all instance of node use process manager on your computer. If it does not work restart the computer.

ValidationError: field: Path field is required

it means you pass no data to the API. Check the api in chrome devtools to see why the payload of this api is empty. then fill that with values to get rid of this error.

if you pass the data but still get error check the api code to see if you extract data from req.body

Subtotal (NAN) items

It happens when item.qty is not a number:

Subtotal ({ Items.reduce((acc, item) => acc + item.qty, 0)})

To fix it check that you wrap qty in Number() to convert string to number in CartScreen.js:

const qty = location.search ? Number(location.search.split('=')[1]) : 1 onChange={(e) => dispatch(addToCart(item.product, Number(e.target.value)))}

Also clear cookie and test again.

PayPal buttons are not loading

you need to check the error on the chrome dev tools to find why. there are some reasons like:

  • Paypal client id does not set correctly in .env file

  • Paypal client id does not load on the frontend in OrderScreen.js

  • Paypal script load multiple times.

For all cases, the best way is to clone this repo and run it on your computer. It works.

https://github.com/bradtraversy/proshop_mern/

Then compare your code with this.

CountInStock is not updating to whatever

This is a new feature called inventory management. It's been noted for future updates. the idea is to find all products in the orderItems and decrease them in a for loop in order create api.

Decrement the count in stock when an order is delivered?

In deliver api use a for loop like this:

 for (const index in order.orderItems) {
      const item = order.orderItems[index];
      const product = await Product.findById(item.product);
      product.countInStock -= item.qty;
      
      await product.save({ session });
    }

Error: listen EADDRINUSE: address already in use :::5000

Close VS Code and all terminals and command prompts. then open app or proccess managaer and close all instances of nodejs, then open VS Code again and run the project. it still getting error restart your computer.

Warning: A component is changing a controlled input of

The reason is, you defined a state that is undefined at first rendering. Because of that, the input field will become uncontrolled. you need to set it to emtpy string to fix this warning.

backslash \ and the image

you need to check uploadRoutes.js at this line:

https://github.com/bradtraversy/proshop_mern/blob/204fa8594e858112aa25e97cff3ec07f94935ea5/backend/routes/uploadRoutes.js#L37

res.send(/${req.file.path})

you can convert it to this

res.send(/${req.file.path.replace(/\\/g, "/")})

Token Protection

we had a bug fix to redirect user to login page after token expiration. the solution for this issue is to use refresh token and having short token time like 30 mins.

to get the idea use this: https://solidgeargroup.com/en/refresh-token-with-jwt-authentication-node-js/

Is this app secure?

there are some rooms to improve the security of this app:

1- make token expiration time short like 30 mins.

2- Use jwt refresh token to re-auth users. https://solidgeargroup.com/en/refresh-token-with-jwt-authentication-node-js/

3- encrypt data in local storage

How to change "Welcome to Proshop" title

We use Meta component to chane the title. here is the component that uses Helmet:

https://github.com/bradtraversy/proshop_mern/blob/master/frontend/src/components/Meta.js#L4

and here is the usage of it:

https://github.com/bradtraversy/proshop_mern/blob/master/frontend/src/screens/HomeScreen.js#L29

"/profile" why do we need to make additional request to the server

because we should save minimum data in local storage. we may need to read more data from user like addresses, etc and it needs a api call to server.

Upload/Replace image but old image still remains in upload folder! Why?

the reason is simplicity. also, it does not happens frequently. to delete the previous file you need to call a DELETE /api/uploads/:filename and run it before uploading the file. in that API use fs.unlink() to delete that file.

Why do we use the spread operator on keyword in productController

aft this line we use req.query.keyword to build a query object in mongoose. because we need to mix this object with other queries we use spread operator.

https://github.com/bradtraversy/proshop_mern/blob/master/backend/controllers/productController.js#L11

TypeError: Cannot read property 'image' of undefined

it means product is null. use this condition in the component to fix this issue:

if (!product) return null;

it this error happens while using redux make sure the data you get from the backend isn't null. you can clone this repo and run it on your computer. It works.

https://github.com/bradtraversy/proshop_mern/

Then compare your code with this.

Add to cart BUG

in cartscreen we check the qty in query string:

const qty = location.search ? Number(location.search.split('=')[1]) : 1

if there is no qty we use 1. that's why you get 1 not 5.

How to reset password

  1. add resetToken and set it to null in the userModel.

  2. create a reset screen to get user email like login screen

  3. check user email and if it exists then create a token and save it in reset token

  4. send email to user with the resetToken as link. use mailgun to send reset email

  5. when user clicks on the link create a new form to reset pass. get pass twice and reset if it is mached.

why redux

error: RangeError: Maximum call stack size exceeded

it happens when the is not array in dep list of useEffect or there is variable that change on useEffect function periodically. you can clone this repo and run it on your computer. It works.

https://github.com/bradtraversy/proshop_mern/

Then compare your code with this.

findDOMNode is deprecated in StrictMode

it is because of an issue in react-paypal-checkout-button-v2 . wait for an update on this package to fix this issue.

What is the point of dispatching getUserDetails

In this case, without getUserDetails it works, but Suppose we are going to have more information about users like their addresses. we can not save them in userInfo in localStorage. we need to fetch them from the backend.

cant see success message in User update profile reset

if we remove 'success' from the condition it won't update the UI.

to fix this issue we can use Toast from react boostrap:

const [showMessage, setShowMessage ] = useState(false);

// in useEffect if (!user || !user.name || success) { if(success) { setShowMessage(true); } dispatch({ type: USER_UPDATE_PROFILE_RESET }) }

// In render
<Toast.Body>Profile updated</Toast.Body> it will be hidden after 3 seconds.

How to use

Also you can clone this repo: git clone https://github.com/bradtraversy/proshop_mern

Then follow this guide to run it locally https://github.com/bradtraversy/proshop_mern#usage

then compare it with your code.

if it does not work for you please share your github repo.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment